These steps cover writing and running your application:
- From your Terminal or console application, create a new directory called ~/projects/go-programming-cookbook/chapter2/signals.
- Navigate to this directory.
- Run the following command:
$ go mod init github.com/PacktPublishing/Go-Programming-Cookbook-Second-Edition/chapter2/signals
You should see a file called go.mod that contains the following:
module github.com/PacktPublishing/Go-Programming-Cookbook-Second-Edition/chapter2/signals
- Copy tests from ~/projects/go-programming-cookbook-original/chapter2/signals, or use this as an opportunity to write some of your own code!
- Create a file called signals.go with the following contents:
package main
import (
"fmt"
"os"
"os/signal"
"syscall"
)
// CatchSig sets up a listener for
// SIGINT interrupts
func CatchSig(ch chan os.Signal, done chan bool) {
// block on waiting for a signal
sig := <-ch
// print it when it's received
fmt.Println("nsig received:", sig)
// we can set up handlers for all types of
// sigs here
switch sig {
case syscall.SIGINT:
fmt.Println("handling a SIGINT now!")
case syscall.SIGTERM:
fmt.Println("handling a SIGTERM in an entirely
different way!")
default:
fmt.Println("unexpected signal received")
}
// terminate
done <- true
}
func main() {
// initialize our channels
signals := make(chan os.Signal)
done := make(chan bool)
// hook them up to the signals lib
signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM)
// if a signal is caught by this go routine
// it will write to done
go CatchSig(signals, done)
fmt.Println("Press ctrl-c to terminate...")
// the program blocks until someone writes to done
<-done
fmt.Println("Done!")
}
- Run the following commands:
$ go build
$ ./signals
- Try running the code and then press Ctrl + C. You should see the following:
$./signals
Press ctrl-c to terminate...
^C
sig received: interrupt
handling a SIGINT now!
Done!
- Try running it again. Then, from a separate Terminal, determine the PID and kill the application:
$./signals
Press ctrl-c to terminate...
# in a separate terminal
$ ps -ef | grep signals
501 30777 26360 0 5:00PM ttys000 0:00.00 ./signals
$ kill -SIGTERM 30777
# in the original terminal
sig received: terminated
handling a SIGTERM in an entirely different way!
Done!
- If you copied or wrote your own tests, go up one directory and run go test. Ensure that all the tests pass.