exec.Cmd.Process.Kill doesn't unblock exec.Cmd.Wait

604 views
Skip to first unread message

Ian Gudger

unread,
Jul 9, 2020, 7:14:33 PM7/9/20
to golang-nuts
I am using Go 1.14 AMD64 on Linux 5.3.0.

When I create a subprocess with exec.Cmd.Start, I can't seem to fully kill it with exec.Cmd.Process.Kill, or at least not to the satisfaction of exec.Cmd.Wait.

I am doing something along the lines of:
cmd := exec.Command(binPath)
if err := cmd.Start(); err != nil {
...
}
if err := cmd.Process.Kill(); err != nil {
...
}
if err := cmd.Wait(); err != nil {
...
}

However, this hangs on Wait. As far as I can tell this shouldn't happen. Any idea what I might be doing wrong?

Ian Lance Taylor

unread,
Jul 9, 2020, 7:16:06 PM7/9/20
to Ian Gudger, golang-nuts
Does the subprocess start any subprocesses itself? Are you capturing
Stdout or Stderr into a bytes.Buffer or similar? See
https://golang.org/issue/23019.

Ian

Ian Gudger

unread,
Jul 9, 2020, 8:52:37 PM7/9/20
to Ian Lance Taylor, golang-nuts
Thanks for pointing me to the bug.

This is happening to me even with nil or *os.File Stdout and Stderr (I tried both). Is there anything that can be done to guarantee that exec.Cmd.Wait won't block indefinitely? I don't think my subprocess is starting any of its own subprocesses, but I am not completely certain.

Ian Lance Taylor

unread,
Jul 10, 2020, 12:39:50 AM7/10/20
to Ian Gudger, golang-nuts
On Thu, Jul 9, 2020 at 5:52 PM Ian Gudger <i...@iangudger.com> wrote:
>
> Thanks for pointing me to the bug.
>
> This is happening to me even with nil or *os.File Stdout and Stderr (I tried both). Is there anything that can be done to guarantee that exec.Cmd.Wait won't block indefinitely? I don't think my subprocess is starting any of its own subprocesses, but I am not completely certain.

If you aren't setting Stdout or Stderr, then it's probably not that issue.

The next debugging step would be to run the program under strace -f,
to verify that the child process is being killed and to find out what
is happening with the wait system call. I agree that what you
describe shouldn't happen.

Ian

Houzuo Guo

unread,
Jul 15, 2020, 2:05:36 AM7/15/20
to golang-nuts
Not a direct answer to your question, but I've come across plenty of issues that prevented reliable termination of external processes (along with their children). Eventually I came to this solution, it's been thoroughly tested in production:

func KillProcess(proc *os.Process)

And similar for Windows:

func KillProcess(proc *os.Process)
Reply all
Reply to author
Forward
0 new messages