dshdb64088 2013-09-05 15:46
浏览 212

如何使用golang goroutine中断子进程

I have a child_process that takes 100 seconds to run. The "master" program will spawn the child_process and either waits for it to finish, or terminates it early.

Here is the code snippet of the master program. It fmt.Println the progress and check its stdin with a goroutine. Once "terminate" is received, the master passes the message to the child_process to interrupt it.

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

The "check_input" function is used in both the master program and child_process. It receives "terminate" message from stdin.

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

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

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

 }

It currently works with goroutine and chan.

My question is whether there is a better way to signal/kill/interrupt the child_process.

  • 写回答

1条回答 默认 最新

  • dskld5423 2013-09-05 16:18
    关注

    You can use syscall.Kill to send a signal to a child process providen you have its pid. For example:

    syscall.Kill(cpid, syscall.SIGHUP)
    

    Of course, the above is *nix specific.

    评论

报告相同问题?

悬赏问题

  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥15 Python3.5 相关代码写作
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗