Last active
November 2, 2018 16:25
-
-
Save williammartin/973d5878d1586d2bd13f650f396818d4 to your computer and use it in GitHub Desktop.
Subreaper reaping main
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"os" | |
"os/exec" | |
"os/signal" | |
"time" | |
"github.com/williammartin/subreaper" | |
"golang.org/x/sys/unix" | |
) | |
func main() { | |
switch os.Args[1] { | |
case "run": | |
parent() | |
case "child": | |
child() | |
case "grandchild": | |
grandchild() | |
default: | |
panic("You must pass an argument") | |
} | |
} | |
func parent() { | |
must(subreaper.Set()) | |
isSubreaper, err := subreaper.IsSubreaper() | |
mustNot(err) | |
fmt.Printf("Is this process a subreaper?: %t\n", isSubreaper) | |
cmd := exec.Command("/proc/self/exe", "child") | |
must(cmd.Run()) | |
sigs := make(chan os.Signal, 1) | |
signal.Notify(sigs, unix.SIGCHLD) | |
<-sigs | |
var status unix.WaitStatus | |
pid, err := unix.Wait4(-1, &status, unix.WNOHANG, nil) | |
mustNot(err) | |
fmt.Printf("Grandchild pid %d exited\n", pid) | |
} | |
func child() { | |
cmd := exec.Command("/proc/self/exe", "grandchild") | |
must(cmd.Start()) | |
} | |
func grandchild() { | |
time.Sleep(time.Second * 20) | |
} | |
func must(err error) { | |
if err != nil { | |
panic(err) | |
} | |
} | |
func mustNot(err error) { | |
must(err) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment