I would like to listen for a OS signal in the background but handle it in the foreground.
Here's example code. The mainloop prints "boop" every second indefinitely. But when an interrupt signal is received, the handler prints "Terminating slowly..." and waits five seconds before terminating the program.
package main
import (
"fmt"
"os"
"os/signal"
"time"
)
func main() {
c := make(chan os.Signal)
signal.Notify(c, os.Interrupt)
go func() {
<-c
fmt.Println("Terminating slowly...")
time.Sleep(time.Duration(5)*time.Second)
os.Exit(0)
}()
for {
fmt.Println("boop")
time.Sleep(time.Duration(1)*time.Second)
}
}
When the signal is being handled, I want everything else to block. But currently during the five seconds of slow termination, it keeps printing "boop".
I get this:
boop
boop
^CTerminating slowly...
boop
boop
boop
boop
boop
I'd like this:
boop
boop
^CTerminating slowly...
The real program is a stack-based-language interpreter where the user can have something run on termination, but currently the mainloop can change the stack at the same time.