반응형
Golang에서 os / exec로 시작된 프로세스 종료
Golang에서 os.exec로 시작된 프로세스를 종료하는 방법이 있습니까? 예를 들어 ( http://golang.org/pkg/os/exec/#example_Cmd_Start에서 ),
cmd := exec.Command("sleep", "5")
err := cmd.Start()
if err != nil {
log.Fatal(err)
}
log.Printf("Waiting for command to finish...")
err = cmd.Wait()
log.Printf("Command finished with error: %v", err)
3 초 후에 해당 프로세스를 미리 종료하는 방법이 있습니까?
미리 감사드립니다
실행 종료 exec.Process:
// Start a process:
cmd := exec.Command("sleep", "5")
if err := cmd.Start(); err != nil {
log.Fatal(err)
}
// Kill it:
if err := cmd.Process.Kill(); err != nil {
log.Fatal("failed to kill process: ", err)
}
exec.Process시간 초과 후 실행 종료 :
// Start a process:
cmd := exec.Command("sleep", "5")
if err := cmd.Start(); err != nil {
log.Fatal(err)
}
// Wait for the process to finish or kill it after a timeout (whichever happens first):
done := make(chan error, 1)
go func() {
done <- cmd.Wait()
}()
select {
case <-time.After(3 * time.Second):
if err := cmd.Process.Kill(); err != nil {
log.Fatal("failed to kill process: ", err)
}
log.Println("process killed as timeout reached")
case err := <-done:
if err != nil {
log.Fatalf("process finished with error = %v", err)
}
log.Print("process finished successfully")
}
프로세스가 종료되고 오류 (있는 경우)가 수신 done되거나 3 초가지나 프로그램이 완료되기 전에 종료됩니다.
선택 및 채널이없는 더 간단한 버전.
func main() {
cmd := exec.Command("cat", "/dev/urandom")
cmd.Start()
timer := time.AfterFunc(1*time.Second, func() {
err := cmd.Process.Kill()
if err != nil {
panic(err) // panic as can't kill a process.
}
})
err := cmd.Wait()
timer.Stop()
// read error from here, you will notice the kill from the
fmt.Println(err)
}
글쎄, 경험 많은 바둑 프로그래머와 상담 한 후, 이것은 분명히 문제를 해결하기에 충분한 방법이 아닙니다. 따라서 허용되는 답변을 참조하십시오.
Here is an even shorter version, and very straight forward. BUT, possibly having tons of hanging goroutines if timeout is long.
func main() {
cmd := exec.Command("cat", "/dev/urandom")
cmd.Start()
go func(){
time.Sleep(timeout)
cmd.Process.Kill()
}()
return cmd.Wait()
}
ReferenceURL : https://stackoverflow.com/questions/11886531/terminating-a-process-started-with-os-exec-in-golang
반응형
'Program Club' 카테고리의 다른 글
| Highcharts 차트 최대 yAxis 값을 설정하는 방법 (0) | 2020.12.15 |
|---|---|
| 헤드리스 모드에서 Chrome을 시작하는 방법은 없나요? (0) | 2020.12.15 |
| 여러 개의 다른 InputStream을 하나의 InputStream으로 연결하는 방법 (0) | 2020.12.15 |
| C-% x 형식 지정자 (0) | 2020.12.15 |
| styles.xml과 themes.xml의 차이점은 무엇입니까? (0) | 2020.12.15 |