【问题标题】:how to interrupt child process with golang goroutine如何使用 golang goroutine 中断子进程
【发布时间】:2013-09-09 13:07:34
【问题描述】:

我有一个运行需要 100 秒的 child_process。 “master”程序将产生 child_process 并等待它完成,或者提前终止它。

这里是主程序的代码sn-p。它fmt.Println 进度并使用 goroutine 检查其stdin。一旦收到“终止”,主进程将消息传递给 child_process 以中断它。

//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

主程序和子进程都使用了“check_input”函数。它从标准输入接收“终止”消息。

//check_input function 
 func check_input(msg chan string){
reader := bufio.NewReader(os.Stdin)
    for {
      line, err := reader.ReadString('\n')

      if err != nil {
        // You may check here if err == io.EOF
        break
      }       

      if strings.TrimSpace(line) == "terminate" {
        msg <- "terminate"
      }
   }

 }

它目前适用于 goroutine 和 chan。

我的问题是是否有更好的方法来发信号/杀死/中断 child_process。

【问题讨论】:

    标签: go


    【解决方案1】:

    您可以使用syscall.Kill 向子进程发送信号,前提是您有它的 pid。例如:

    syscall.Kill(cpid, syscall.SIGHUP)
    

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

    【讨论】:

    • child_process.Process.Kill()child_process.Process.Signal(os.Interrupt) 如果你想跨平台...
    • 请允许我问一下 child_process 是否会得到 kill 信号并在被杀死之前有时间清理自己。
    • 不是用kill,而是用child_process.Process.Signal(os.Interrupt)。但是,如果它在发送中断后的某个时间没有自行结束,你应该考虑杀死它
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-07
    • 2022-01-16
    • 1970-01-01
    • 1970-01-01
    • 2016-08-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多