-
Notifications
You must be signed in to change notification settings - Fork 6
/
proc.go
95 lines (86 loc) · 1.66 KB
/
proc.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
package main
import (
"bytes"
"context"
"fmt"
"os/exec"
"syscall"
"time"
)
type process struct {
*exec.Cmd
ctx context.Context
buf *bytes.Buffer
}
func NewProcess(ctx context.Context, buf *bytes.Buffer, name string, args ...string) *process {
p := &process{
Cmd: exec.Command(name, args...),
ctx: ctx,
buf: buf,
}
p.Stdout = p.buf
p.Stderr = p.buf
return p
}
func (p *process) Pid() int {
if p.Process != nil {
return p.Process.Pid
} else {
return -1
}
}
func (p *process) Wait() error {
// monitor process
go p.monitor()
// wait for exit
if err := p.Cmd.Wait(); err != nil {
fmt.Println("exec worker err", p.Pid(), err.Error(), p.buf.String())
return err
}
//
fmt.Println("worker done:", p.Pid(), p.buf.String())
return nil
}
func (p *process) monitor() error {
for {
select {
case <-p.ctx.Done():
fmt.Println("worker cancel from monitor", p.Pid())
return StopProcess(p.Pid())
default:
if p.ProcessState != nil && p.ProcessState.Exited() {
fmt.Println("worker done from monitor", p.Pid())
return nil
} else {
time.Sleep(time.Second)
}
}
}
}
func StopProcess(pid int) error {
if pid < 0 {
return nil
}
// send signal to process
if syscall.Kill(pid, syscall.SIGINT) == syscall.ESRCH {
return nil
}
// wait 10 seconds for exiting
for i := 0; i < 10; i++ {
time.Sleep(time.Second)
if syscall.Kill(pid, syscall.Signal(0)) == syscall.ESRCH {
return nil
}
}
// force kill
if syscall.Kill(pid, syscall.SIGKILL) == syscall.ESRCH {
return nil
}
time.Sleep(time.Second)
// try again
if err := syscall.Kill(pid, syscall.Signal(0)); err == syscall.ESRCH {
return nil
} else {
return err
}
}