本文介绍了终止进程在Golang中使用os / exec开始的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在Golang中终止一个以os.exec开头的进程?例如(来自),

  cmd:= exec.Command(sleep,5)
err:= cmd.Start()
if err!= nil {
log.Fatal(err)
}
log.Printf(Waiting for command to finish ...)
err = cmd.Wait()
log.Printf(Command with error:%v,err)

有没有办法提前终止该过程,也许3秒后?

预先感谢

exec.Process :



<$ p $ = >解决方案


cmd:= exec.Command(sleep,5)
if err:= cmd.Start(); err!= nil {
log.Fatal(err)
}

//杀死它:
if err:= cmd.Process.Kill(); err!= nil {
log.Fatal(杀死进程失败:,err)
}

超时后终止正在运行的 exec.Process

  //启动一个进程:
cmd:= exec.Command(sleep,5)
if err:= cmd.Start(); err!= nil {
log.Fatal(err)
}

//等待进程结束或在超时后终止它:
done:= make(chan error,1)
去func(){
完成< - cmd.Wait()
}()
select {
case< - time.After(3 * time.Second):
if err:= cmd.Process.Kill(); err!= nil {
log.Fatal(杀死进程失败:,错误)
}
log.Println(进程杀死超时达到)
case err :=< -done:
if err!= nil {
log.Fatalf(process finished with error =%v,err)
}
log.Print 过程完成成功)
}

过程结束并且它的错误(如果有的话) )是通过 done 接收的,或者3秒过去了,程序在完成之前被杀死。


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.Command("sleep", "5")
err := cmd.Start()
if err != nil {
    log.Fatal(err)
}
log.Printf("Waiting for command to finish...")
err = cmd.Wait()
log.Printf("Command finished with error: %v", err)

Is there a way to terminate that process ahead of time, perhaps after 3 seconds?

Thanks in advance

解决方案

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:
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.

这篇关于终止进程在Golang中使用os / exec开始的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 18:01