실행하는 데 100 초가 걸리는 child_process가 있습니다. "마스터"프로그램은 child_process를 생성하고 완료 될 때까지 기다리거나 초기에 종료합니다.golang goroutine을 사용하여 하위 프로세스를 중단하는 방법
다음은 마스터 프로그램의 코드 스 니펫입니다. 그것 fmt.Println
진행 및 그 stdin
goroutine 확인하십시오. "종료"가 수신되면 마스터는 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"기능은 마스터 프로그램과 child_process에서 모두 사용됩니다. stdin에서 "terminate"메시지를받습니다.
//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 여부입니다.
당신이 크로스 플랫폼이되고 싶다면'child_process.Process.Kill()'또는'child_process.Process.Signal (os.Interrupt)'... –
내가 child_process가 kill 신호를 얻을 것인지 그리고 살해되기 전에 스스로 청소할 시간이 있어야합니다. –
죽이지는 않지만'child_process.Process.Signal (os.Interrupt)'를 사용하십시오. 그러나 인터럽트를 보낸 후 언젠가 스스로 끝나지 않으면 죽이는 것을 고려해야합니다. –