英文:
Auto kill child process when parent process is died
问题
在Golang中,当父进程终止时,如何自动终止子进程?子进程是通过exec.Command()调用的。
例如,父进程的进程ID是28290,有三个子进程:32062、32473、33455。
ps axo pid, ppid, pgid | grep 28290
PID PPID PGID
28290 1 28289
32062 28290 28289
32473 28290 28289
33455 28290 28289
这四个进程具有相同的PGID=28289。
当我杀死父进程28290(在Linux中使用kill命令,kill -9 28290)时,子进程不会退出()。
是否有任何选项可以自动终止子进程?
英文:
How to auto kill child process when parent process is died in Golang ?
The child process is invoked by exec.Command().
For example,
The parent process pid is: 28290, there is three child process: 32062, 32473, 33455.
# ps axo pid, ppid, pgid | grep 28290
PID PPID PGID
28290 1 28289
32062 28290 28289
32473 28290 28289
33455 28290 28289
The four process have the same PGID=28289.
When I kill the parent process 28290(kill the 28290 in linux, kill -9 28290), the child processes does not exit().
Is there any options to auto kill the child processes?
答案1
得分: 1
在运行命令之前设置进程组ID,并通过-pid进行终止,注意减号。
// 设置pgid,以便可以一起终止所有子进程
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
...
// 终止-pgid(-pid)
syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
英文:
Set process group ID before running the command, and kill by -pid, pay attention to the minus sign.
// set pgid so all child processes can be killed together
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
...
// kill -pgid (-pid)
syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论