Terminating a Process Started with os/exec in Golang

后端 未结 3 1791
情歌与酒
情歌与酒 2020-12-07 10:24

Is there a way to terminate a process started with os.exec in Golang? For example (from http://golang.org/pkg/os/exec/#example_Cmd_Start),

cmd := exec.Comma         


        
3条回答
  •  醉梦人生
    2020-12-07 11:08

    A simpler version without select and channels.

    func main() {
        cmd := exec.Command("cat", "/dev/urandom")
        cmd.Start()
        timer := time.AfterFunc(1*time.Second, func() {
            err := cmd.Process.Kill()
            if err != nil {
                panic(err) // panic as can't kill a process.
            }
        })
        err := cmd.Wait()
        timer.Stop()
    
        // read error from here, you will notice the kill from the 
        fmt.Println(err)
    }
    

    Well, after consulting some experienced go programmer, this is apparently not a GOly enough way to solve the problem. So please refer to the accepted answer.


    Here is an even shorter version, and very straight forward. BUT, possibly having tons of hanging goroutines if timeout is long.

    func main() {
        cmd := exec.Command("cat", "/dev/urandom")
        cmd.Start()
        go func(){
            time.Sleep(timeout)
            cmd.Process.Kill()
        }()
        return cmd.Wait()
    }
    

提交回复
热议问题