我有一个需要 100 秒才能运行的child_process。"主"程序将生成child_process,并等待它完成,或者提前终止它。
这是主程序的代码片段。它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("terminaten"))
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"功能在主程序和child_process中使用。它从标准输入接收"终止"消息。
//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。
您可以使用
syscall.Kill
向子进程发送信号,前提是您有其 pid。例如:
syscall.Kill(cpid, syscall.SIGHUP)
当然,以上是*nix特定的。