This repository has been archived by the owner on Jul 28, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 67
/
process.go
84 lines (74 loc) · 1.8 KB
/
process.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
package process
import (
"fmt"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"syscall"
"time"
)
func SignalAndCleanup(pidfile, match string, signal syscall.Signal) error {
pidBytes, err := ioutil.ReadFile(pidfile)
if err != nil {
if os.IsNotExist(err) {
return nil
}
return fmt.Errorf("failed to read pidfile %s", pidfile)
}
pid, err := strconv.Atoi(string(pidBytes))
if err != nil {
return fmt.Errorf("%s did not contain an integer", pidfile)
}
if running, err := isRunning(pid); err != nil {
return fmt.Errorf("failed to send signal to %s", filepath.Base(pidfile))
} else if !running {
return os.Remove(pidfile)
}
// get process form pid
cmd := exec.Command("ps", "-p", string(pidBytes), "-o", "command=")
output, err := cmd.Output()
if err == nil && !strings.Contains(string(output), match) {
// Process pid is running, but is not us
return os.Remove(pidfile)
}
if err := syscall.Kill(pid, signal); err != nil {
return fmt.Errorf("failed to send signal to %s", filepath.Base(pidfile))
}
if err := waitForPidTermination(pid); err != nil {
return err
}
return os.Remove(pidfile)
}
func isRunning(pid int) (bool, error) {
err := syscall.Kill(pid, syscall.Signal(0))
if err != nil {
if e, ok := err.(syscall.Errno); ok && e == syscall.ESRCH {
return false, nil
}
return false, err
}
return true, nil
}
func waitForPidTermination(pid int) error {
timeout := time.After(time.Minute)
tick := time.NewTicker(time.Millisecond)
defer tick.Stop()
for {
select {
case <-timeout:
return fmt.Errorf("timed out waiting for process to exit")
case <-tick.C:
err := syscall.Kill(pid, syscall.Signal(0))
if err != nil {
if e, ok := err.(syscall.Errno); ok && e == syscall.ESRCH {
return nil
}
return err
}
}
}
return nil
}