proc.Kill() on Windows

821 views
Skip to first unread message

clyq fs

unread,
Apr 26, 2012, 5:00:49 AM4/26/12
to golang-nuts
I tried to stop a waiting process in a goroutine by this on Windows.
But it ends up killing the program immediately. What's your
suggestion? Thanks.


package main

import (
"log"
"os"
"os/exec"
"time"
)

func wait(ch chan *os.Process) {
log.Println(`adb wait-for-device`)

cmd := exec.Command(`adb`, `wait-for-device`)
if err := cmd.Start(); err != nil {
log.Fatal(err)
}
ch <- cmd.Process

if err := cmd.Wait(); err != nil {
log.Fatal(err)
}
}

func main() {
ch := make(chan *os.Process)
go wait(ch)
proc := <-ch
time.Sleep(time.Second * 2)
log.Println("Kill")
proc.Kill()
log.Println("Killed")
time.Sleep(time.Second * 2)
log.Println("Exit")
}


2012/04/26 16:54:52 adb wait-for-device
2012/04/26 16:54:54 Kill
2012/04/26 16:54:54 Killed
2012/04/26 16:54:54 exit status 1

Dave Cheney

unread,
Apr 26, 2012, 6:57:48 AM4/26/12
to clyq fs, golang-nuts
> I tried to stop a waiting process in a goroutine by this on Windows.
> But it ends up killing the program immediately. What's your
> suggestion? Thanks.

Your program exited when your main goroutine executed

proc.Kill()

Causing this code in your worker goroutine to run

 if err := cmd.Wait(); err != nil {
               log.Fatal(err)
   }

There is a race between log.Fatal() and your final log.Println(). When
you kill a subprocess, it will always exit with a non zero exit code
if it has not already completed.

Cheers

Dave

clyq fs

unread,
Apr 26, 2012, 9:36:34 AM4/26/12
to Dave Cheney, golang-nuts
the subprocess in goroutine suppose to wait at least two secs, then killed, but the main is also killed rather than wait another two secs then exit. I would like to know if there is a way prevent parent process being killed.

thanks

Dave Cheney

unread,
Apr 26, 2012, 9:44:18 AM4/26/12
to clyq fs, golang-nuts
How do you know the parent is being killed? I read it as exiting after log.Fatal. 

Jiří Zárevúcky

unread,
Apr 26, 2012, 9:48:04 AM4/26/12
to golan...@googlegroups.com, Dave Cheney
On Thursday, 26 April 2012 15:36:34 UTC+2, fs wrote:
the subprocess in goroutine suppose to wait at least two secs, then killed, but the main is also killed rather than wait another two secs then exit. I would like to know if there is a way prevent parent process being killed.

As has already been explained, the call to Kill() doesn't kill the parent process.. you do.

log.Fatal() implicitly terminates the entire process.

fs

unread,
Apr 26, 2012, 10:21:38 AM4/26/12
to golang-nuts
Ah, log.Fatal calls os.Exit(1).

Thanks a lot!
Reply all
Reply to author
Forward
0 new messages