启动一个 goroutine 等待进程,使用 select 等待 goroutine 完成的消息或超时处理。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package main
import (
"context"
"fmt"
"log"
"os/exec"
"time"
)
func main() {
ctx, cancel := context.WithCancel(context.Background())
done := make(chan struct{})
cmd := exec.CommandContext(ctx, "sleep", "300")
go func() {
defer close(done)
err := cmd.Start()
if err != nil {
log.Fatal(err)
}
err = cmd.Wait()
if err != nil {
log.Println("waiting on cmd:", err)
}
}()
select {
case <-done:
// cmd.Wait() completed.
case <-time.After(3 * time.Second):
fmt.Println("Exit Signal")
_ = cmd.Process.Kill()
}
cancel()
}
本文网址: https://golangnote.com/topic/279.html 转摘请注明来源