Skip to content

Instantly share code, notes, and snippets.

@lox
Created May 4, 2017 03:27
Show Gist options
  • Save lox/dada3113a8316bf46d23cddc0ee27b19 to your computer and use it in GitHub Desktop.
Save lox/dada3113a8316bf46d23cddc0ee27b19 to your computer and use it in GitHub Desktop.
Test of process group signalling
package main
import (
"fmt"
"os"
"os/exec"
"os/signal"
"syscall"
"time"
)
func main() {
cmd := exec.Command("/bin/bash", "./test-3.sh")
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
signals := make(chan os.Signal, 1)
signal.Notify(signals, os.Interrupt,
syscall.SIGHUP,
syscall.SIGTERM,
syscall.SIGINT,
syscall.SIGQUIT)
go func() {
// Pass signals to the sub-process
for sig := range signals {
if cmd.Process != nil {
syscall.Kill(-cmd.Process.Pid, sig.(syscall.Signal))
}
}
}()
defer signal.Stop(signals)
start := time.Now()
err := cmd.Run()
fmt.Printf("pid=%d duration=%s err=%s\n", cmd.Process.Pid, time.Since(start), err)
}
#!/bin/bash
if [ -z "${PS1-}" ] ; then
echo non-interactive
else
echo interactive
fi
# Blocks using sleep, and sleeps in the signal handlers
handle_int() {
echo "Received INT. Sleeping for 5...";
sleep 5;
echo "Finished.";
exit 0
}
handle_term() {
echo "Received TERM. Sleeping for 5...";
sleep 5;
echo "Finished.";
exit 0
}
trap handle_int INT
trap handle_term TERM
trap 'echo "doing some cleaning"' EXIT
echo "Sleeping for 60..."
sleep 60
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment