在 Golang 中终止以 os/exec 启动的进程
技术问答
288 人阅读
|
0 人回复
|
2023-09-12
|
没有办法Golang 中终止以 os.exec 启动过程?例如(来自)http://golang.org/pkg/os/exec/#example_Cmd_Start),2 T1 [! D- w1 W
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)7 c. D7 r& m' Y& m9 Y- U' L; j L8 d
3 秒后有没有办法提前终止过程?/ V( k' N2 [" |8 P5 G; k& i9 e
提前致谢& X( M v* ~% q+ o9 N
& h+ f" ?2 g d ?$ i) t+ ~/ r 解决方案: 4 D. v6 G/ b7 T8 c3 z
运行并终止一个exec.Process:
' I6 W; F0 R& {( S( `// 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)}
/ Z8 M5 H1 Z& e C3 E9 @6 ?* e7 p/ K exec.Process超时后操作终止:
2 g0 Y1 p8 k! [( R+ rctx,cancel := context.WithTimeout(context.Background(),3 * time.Second)defer cancel()if err := exec.CommandContext(ctx,"sleep","5").Run(); err != nil / This will fail after 3 seconds. The 5 second sleep // will be interrupted.}. P2 g6 Q/ X( |& U/ S/ k- F- F
请参阅Go 文档中的这个例子* Q% z* ^# e9 |7 p, i
遗产! A5 F! E5 u* O5 A) C& W- \2 W N, ]/ ?
在 Go 1.在7 之前,我们没有这个context包,答案不一样。8 j/ ]) a3 _7 u! J
exec.Process使用通道和 goroutine 在超时后运行和终止:- W3 n+ m( d* s* U3 ^1 t) v
[code]// 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 要么过程结束并收到它的错误(如果有),done或者已经过去了3 秒,程序在完成前终止。 |
|
|
|
|
|