为什么通过exec.Start()创建的进程在其父进程被SIGINT信号杀死后会退出?

huangapple go评论83阅读模式
英文:

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

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.

huangapple
  • 本文由 发表于 2013年10月8日 17:05:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/19243431.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定