-
Notifications
You must be signed in to change notification settings - Fork 2
/
timeout.go
99 lines (87 loc) · 1.76 KB
/
timeout.go
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package main
import (
"flag"
"fmt"
"io"
"log"
"os"
"os/exec"
"os/signal"
"sync"
"syscall"
"time"
)
var (
flagDuration = flag.String("duration", "", "exit after this duration")
)
func main() {
flag.Parse()
args := flag.Args()
if len(args) == 0 {
log.Fatal("No command specified")
}
cmd := exec.Command(args[0], args[1:]...)
var wg sync.WaitGroup
opr, opw := io.Pipe()
cmd.Stdout = opw
epr, epw := io.Pipe()
cmd.Stderr = epw
err := cmd.Start()
if err != nil {
log.Fatal(err)
}
wg.Add(2)
go func() {
defer wg.Done()
io.Copy(os.Stdout, opr)
}()
go func() {
defer wg.Done()
io.Copy(os.Stderr, epr)
}()
sigint := make(chan os.Signal, 1)
signal.Notify(sigint, syscall.SIGINT)
// Use a channel to signal completion so we can use a select statement
done := make(chan error)
go func() { done <- cmd.Wait() }()
// Start a timer
var timeout <-chan time.Time
if *flagDuration != "" {
d, err := time.ParseDuration(*flagDuration)
if err != nil {
log.Fatalf("unable to parse duration: %v", err)
}
timeout = time.After(d)
}
// The select statement allows us to execute based on which channel
// we get a message from first.
defer wg.Wait()
wait:
for {
select {
case <-timeout:
// Timeout happened first, kill the process and print a message.
fmt.Println("timeout reached...")
err := cmd.Process.Signal(os.Kill)
if err != nil {
fmt.Println("Problem killing:", err)
os.Exit(1)
}
case err := <-done:
if err != nil {
fmt.Println("Non-zero exit code:", err)
os.Exit(1)
}
break wait
case <-sigint:
fmt.Println("Got SIGINT. Sending Kill to child")
err := cmd.Process.Signal(os.Kill)
if err != nil {
fmt.Println("Problem killing:", err)
os.Exit(1)
}
}
}
opw.Close()
epw.Close()
}