doutuo3575 2017-08-28 15:29
浏览 305
已采纳

如何强制golang关闭打开的管道

I have to process a long output of a script and find some data. This data most likely will be located at the almost very beginning of the output. After data found I do not need to process output anymore and can quit.

The issue that I cannot stop processing output because exec.Cmd does not have any function to close opened command.

Here are some simplified code (error handling was ommited):

func processOutput(r *bufio.Reader)(){
   for {
      line, _, err := r.ReadLine()
      if some_condition_meet {
         break
      }
      ......
   }
   return
}

func execExternalCommand(){
   cmdToExecute := "......"
   cmd := exec.Command("bash", "-c", cmdToExecute)
   output, _ := cmd.StdoutPipe()

   cmd.Start()
   r := bufio.NewReader(output)
   go processOutput(r)
   cmd.Wait()
   return
}  

What should I do at the end at processOutput function to stop cmd? Maybe there is another way how to solve it.

Thanks

  • 写回答

2条回答 默认 最新

  • drkwpgrdb092239314 2017-08-28 15:35
    关注

    As it stands, you can't do this from processOutput because all it receives is a bufio.Reader. You would need to pass the exec.Cmd to it for it to do anything with the forked process.

    To kill the forked process, you can send it a signal, e.g.: cmd.Process.Kill() or cmd.Process.Signal(os.SIGINT). See documentation on exec.Cmd and os.Process.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!