4

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

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

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

4

1 回答 1

0

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

syscall.Kill(cpid, syscall.SIGHUP)

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

于 2013-09-05T16:18:25.447 回答