2

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?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
loverszhaokai
  • 127
  • 10

1 Answers1

1

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)
Hal Wang
  • 11
  • 3