/
worker.go
78 lines (70 loc) · 1.68 KB
/
worker.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
package proc
import (
"io"
"os"
"os/exec"
"runtime"
"syscall"
"github.com/cybriq/qu"
)
type Worker struct {
Cmd *exec.Cmd
Args []string
// Stderr io.WriteCloser
// StdPipe io.ReadCloser
StdConn *StdConn
}
// Spawn starts up an arbitrary executable file with given arguments and
// attaches a connection to its stdin/stdout
func Spawn(quit qu.C, args ...string) (w *Worker, e error) {
w = &Worker{
Cmd: exec.Command(args[0], args[1:]...),
Args: args,
}
var cmdOut io.ReadCloser
if cmdOut, e = w.Cmd.StdoutPipe(); log.E.Chk(e) {
return
}
var cmdIn io.WriteCloser
if cmdIn, e = w.Cmd.StdinPipe(); log.E.Chk(e) {
return
}
w.StdConn = New(cmdOut, cmdIn, quit)
w.Cmd.Stderr = os.Stderr
if e = w.Cmd.Start(); log.E.Chk(e) {
}
return
}
// Wait for the process to finish running
func (w *Worker) Wait() (e error) {
return w.Cmd.Wait()
}
// Interrupt the child process.
// This invokes kill on windows because windows doesn't have an interrupt
// signal.
func (w *Worker) Interrupt() (e error) {
if runtime.GOOS == "windows" {
if e = w.Cmd.Process.Kill(); log.E.Chk(e) {
}
return
}
if e = w.Cmd.Process.Signal(syscall.SIGINT); !log.E.Chk(e) {
log.D.Ln("interrupted")
}
return
}
// Kill forces the child process to shut down without cleanup
func (w *Worker) Kill() (e error) {
if e = w.Cmd.Process.Kill(); !log.E.Chk(e) {
log.D.Ln("killed")
}
return
}
// Stop signals the worker to shut down cleanly.
//
// Note that the worker must have handlers for os.Signal messages.
//
// It is possible and neater to put a quit method in the IPC API and use the quit channel built into the StdConn
func (w *Worker) Stop() (e error) {
return w.Cmd.Process.Signal(os.Interrupt)
}