Skip to content

Instantly share code, notes, and snippets.

@djoreilly
Last active August 26, 2021 16:01
Show Gist options
  • Save djoreilly/f82c2f29bb0dc501f6b957d705037404 to your computer and use it in GitHub Desktop.
Save djoreilly/f82c2f29bb0dc501f6b957d705037404 to your computer and use it in GitHub Desktop.
Prevent shell from sending signals to children and detect if signals caught
package main
import (
"fmt"
"os"
"os/exec"
"os/signal"
"syscall"
"time"
)
func interrupted(sigCh <-chan os.Signal) bool {
// non-blocking read on channel
select {
case <-sigCh:
default:
return false // channel is empty
}
return true
}
func main() {
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)
fmt.Println("about to sleep")
startTime := time.Now()
cmd := exec.Command("sleep", "5")
// prevent the shell from signalling children https://stackoverflow.com/a/33171307
cmd.SysProcAttr = &syscall.SysProcAttr{
Setpgid: true,
}
cmd.Run()
fmt.Printf("slept for %0.0f sec\n", time.Now().Sub(startTime).Seconds())
if interrupted(sigCh) {
fmt.Println("interrupted")
} else {
fmt.Println("not interrupted")
}
}
$ go run interrupted.go
about to sleep
^C^C^C
slept for 5 sec
interrupted
$ go run interrupted.go
about to sleep
slept for 5 sec
not interrupted
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment