Simple linux signal handler for Go
go get -u github.com/syossan27/tebata
package main
import (
"fmt"
"os"
"strconv"
"syscall"
"github.com/syossan27/tebata"
)
func main() {
t := tebata.New(syscall.SIGINT, syscall.SIGTERM)
// Do function when catch signal.
// Always check for errors when reserving functions
if err := t.Reserve(sum, 1, 2); err != nil {
fmt.Printf("Failed to reserve sum function: %v\n", err)
return
}
if err := t.Reserve(hello); err != nil {
fmt.Printf("Failed to reserve hello function: %v\n", err)
return
}
if err := t.Reserve(os.Exit, 0); err != nil {
fmt.Printf("Failed to reserve exit function: %v\n", err)
return
}
fmt.Println("Signal handler registered. Press Ctrl+C to trigger.")
// Use select{} for a non-CPU-consuming infinite wait
select {}
}
func sum(firstArg, secondArg int) {
fmt.Println(strconv.Itoa(firstArg + secondArg))
}
func hello() {
fmt.Println("Hello")
}
// Expect output when type Ctrl + C:
// 3
// Hello
The Reserve
method returns an error if:
- The provided function is not a valid function
- The argument types don't match the function parameter types
- Too few or too many arguments are provided
Always check the error return value when calling Reserve
to ensure your signal handlers are properly registered.
Look this article.
How to implement a signal handler in Go
The Go gopher was designed by Renée French.
The gopher side portrait is designed by Takuya Ueda.
Licensed under the "Creative CommonsAttribution 3.0" license.