Skip to content

Instantly share code, notes, and snippets.

@siburu
Created April 28, 2016 09:33
Show Gist options
  • Save siburu/fe98cf04fa04700de0baff7c3d1681fb to your computer and use it in GitHub Desktop.
Save siburu/fe98cf04fa04700de0baff7c3d1681fb to your computer and use it in GitHub Desktop.
Fork and wait for a child in Golang
package main
import (
"os"
"syscall"
"time"
)
const (
CHILD_ARG = "child"
)
func main() {
if len(os.Args) >= 2 && os.Args[1] == CHILD_ARG {
println("I'm a child.")
<-time.After(3 * time.Second)
println("Child dies now.")
return
}
println("I'm a parent.")
pid, err := syscall.ForkExec(os.Args[0], []string{os.Args[0], CHILD_ARG}, &syscall.ProcAttr{Files: []uintptr{0, 1, 2}})
if err != nil {
panic(err.Error())
}
proc, err := os.FindProcess(pid)
if err != nil {
panic(err.Error())
}
state, err := proc.Wait()
if err != nil {
panic(err.Error())
}
println("string:", state.String())
println("pid:", state.Pid())
println("Parent dies now.")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment