Terminating a Process Started with os/exec in Golang

后端 未结 3 1807
情歌与酒
情歌与酒 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 10:54

    Terminating a running exec.Process:

    // Start a process:
    cmd := exec.Command("sleep", "5")
    if err := cmd.Start(); err != nil {
        log.Fatal(err)
    }
    
    // Kill it:
    if err := cmd.Process.Kill(); err != nil {
        log.Fatal("failed to kill process: ", err)
    }
    

    Terminating a running exec.Process after a timeout:

    // Start a process:
    cmd := exec.Command("sleep", "5")
    if err := cmd.Start(); err != nil {
        log.Fatal(err)
    }
    
    // Wait for the process to finish or kill it after a timeout (whichever happens first):
    done := make(chan error, 1)
    go func() {
        done <- cmd.Wait()
    }()
    select {
    case <-time.After(3 * time.Second):
        if err := cmd.Process.Kill(); err != nil {
            log.Fatal("failed to kill process: ", err)
        }
        log.Println("process killed as timeout reached")
    case err := <-done:
        if err != nil {
            log.Fatalf("process finished with error = %v", err)
        }
        log.Print("process finished successfully")
    }
    

    Either the process ends and its error (if any) is received through done or 3 seconds have passed and the program is killed before it's finished.

提交回复
热议问题