英文:
Why process created by exec.Start() quits if its parent is killed by SIGINT?
问题
我在golang中发现了一个奇怪的问题。通过exec.Start()
执行的程序,如果父程序被os.Interrupt
信号中断,那么子程序会退出,而如果父程序正常退出,子程序则不会退出。这两种情况有什么区别呢?
例如:
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
}
在后一种情况下,如果我们没有中断主程序,那么sleep 100000
的父进程将在20秒后成为init
进程。
英文:
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.
答案1
得分: 14
发生的情况是,如果你发送一个进程的SIGINT信号(例如os.Interrupt),同一进程组中的所有进程(包括子进程)也会收到该信号- SIGINT默认会终止一个进程。
然而,如果父进程正常退出,而不是因为SIGINT或类似的原因,同一进程组中的进程不会收到任何信号- 它将继续运行,但会被init进程接管。这不仅适用于Go。
英文:
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.
答案2
得分: 0
Start
方法启动指定的命令,但不等待其完成。
而:
Run
方法启动指定的命令,并等待其完成。
因此,当Go(父)进程退出时,Start
方法只会将进程交给操作系统处理。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论