当父进程死亡时自动终止子进程

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

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)

huangapple
  • 本文由 发表于 2017年8月8日 11:55:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/45559019.html
匿名

发表评论

匿名网友

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

确定