Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/go/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用golang goroutine中断子进程_Go - Fatal编程技术网

如何使用golang goroutine中断子进程

如何使用golang goroutine中断子进程,go,Go,我有一个child_进程,需要100秒才能运行。“主”程序将生成子_进程,并等待它完成,或提前终止它 下面是主程序的代码片段。它fmt.Println进程,并用goroutine检查其stdin。一旦接收到“终止”,主进程将消息传递给子进程以中断消息 //master program message := make(chan string) go check_input(message) child_process := exec.Command("child_process") child_

我有一个child_进程,需要100秒才能运行。“主”程序将生成子_进程,并等待它完成,或提前终止它

下面是主程序的代码片段。它
fmt.Println
进程,并用goroutine检查其
stdin
。一旦接收到“终止”,主进程将消息传递给子进程以中断消息

//master program
message := make(chan string)
go check_input(message)

child_process := exec.Command("child_process")
child_stdin := child_process.StdinPipe()

child_process.Start()    //takes 100 sec to finish

loop:
  for i=:1;i<=100;i++ {
       select {
           case <- message:
               //end child process
               child_stdin.Write([]byte("terminate\n"))
               break loop
           case <- time.After(1*time.Second):
               fmt.Println(strconv.ItoA(i) + " % Complete")  // update progress bar


  }
child_process.Wait()  //wait for child_process to be interrupted or finish
//主程序
消息:=make(chan字符串)
去检查输入(信息)
子进程:=执行命令(“子进程”)
child_stdin:=child_进程.StdinPipe()
child_process.Start()//完成需要100秒
循环:
对于i=:1;i您可以使用向子进程发送信号,前提是您有其pid。例如:

syscall.Kill(cpid, syscall.SIGHUP)

当然,以上是*nix特定的。

子进程.process.Kill()
子进程.process.Signal(os.Interrupt)
如果您想跨平台…请允许我问一下,子进程是否会得到Kill信号,在被杀死之前是否有时间清理自己。不是用Kill,但是使用
子进程.process.Signal(os.Interrupt)
。但是,如果在发送中断后没有结束,则应该考虑杀死它。
syscall.Kill(cpid, syscall.SIGHUP)