I found a strange problem in golang.The program executed by exec.Start()
will quit if the parent program is interrupt by the signal os.Interrupt,while the child program will NOT quit if the parent program exit normally.What's the difference between that two conditions? For examples:
package main
import "fmt"
import "os"
import "time"
import "os/exec"
func main(){
cmd := exec.Command("sleep", "100000")
cmd.Env = os.Environ()
fmt.Println(cmd.Env)
cmd.Start()
time.Sleep(1e9*20)
return
}
In the later condition the parent of sleep 100000
will be the init process
after 20s if we didn't interrupt the main program.
What's happening is that if you send a process SIGINT (as e.g. os.Interrupt does), all proceses in the same process group will also get that signal (which includes child processes) - SIGINT will by default terminate a process.
If however a parent process exits normally, not because of SIGINT or similar, a process in the same process group does not get any signal - it will continue to run, but be adopted by the init process. This is not specific to Go.
I think this is because you're using Start
instead of Run
.
Start starts the specified command but does not wait for it to complete.
whereas:
Run starts the specified command and waits for it to complete.
Therefore Start
will just handover the process to the operating system when the Go (parent) process exits.