-
Notifications
You must be signed in to change notification settings - Fork 414
/
exec.go
74 lines (61 loc) · 1.52 KB
/
exec.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
package main
import (
"log"
"os"
"os/exec"
"os/signal"
"syscall"
"time"
"golang.org/x/net/context"
)
func runCmd(ctx context.Context, cancel context.CancelFunc, cmd string, args ...string) {
defer wg.Done()
process := exec.Command(cmd, args...)
process.Stdin = os.Stdin
process.Stdout = os.Stdout
process.Stderr = os.Stderr
// start the process
err := process.Start()
if err != nil {
log.Fatalf("Error starting command: `%s` - %s\n", cmd, err)
}
// Setup signaling
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGKILL)
wg.Add(1)
go func() {
defer wg.Done()
select {
case sig := <-sigs:
log.Printf("Received signal: %s\n", sig)
signalProcessWithTimeout(process, sig)
cancel()
case <-ctx.Done():
// exit when context is done
}
}()
err = process.Wait()
cancel()
if err == nil {
log.Println("Command finished successfully.")
} else {
log.Printf("Command exited with error: %s\n", err)
// OPTIMIZE: This could be cleaner
os.Exit(err.(*exec.ExitError).Sys().(syscall.WaitStatus).ExitStatus())
}
}
func signalProcessWithTimeout(process *exec.Cmd, sig os.Signal) {
done := make(chan struct{})
go func() {
process.Process.Signal(sig) // pretty sure this doesn't do anything. It seems like the signal is automatically sent to the command?
process.Wait()
close(done)
}()
select {
case <-done:
return
case <-time.After(10 * time.Second):
log.Println("Killing command due to timeout.")
process.Process.Kill()
}
}