-
Notifications
You must be signed in to change notification settings - Fork 148
/
process.go
82 lines (66 loc) · 1.42 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
package tableflip
import (
"fmt"
"os"
"os/exec"
"runtime"
"syscall"
)
var initialWD, _ = os.Getwd()
type process interface {
fmt.Stringer
Signal(sig os.Signal) error
Wait() error
}
type osProcess struct {
*os.Process
finished bool
}
func newOSProcess(executable string, args []string, files []*os.File, env []string) (process, error) {
executable, err := exec.LookPath(executable)
if err != nil {
return nil, err
}
fds := make([]uintptr, 0, len(files))
for _, file := range files {
fd, err := sysConnFd(file)
if err != nil {
return nil, err
}
fds = append(fds, fd)
}
attr := &syscall.ProcAttr{
Dir: initialWD,
Env: env,
Files: fds,
}
args = append([]string{executable}, args...)
pid, _, err := syscall.StartProcess(executable, args, attr)
if err != nil {
return nil, fmt.Errorf("fork/exec: %s", err)
}
// Ensure that fds stay valid until after StartProcess finishes.
runtime.KeepAlive(files)
proc, err := os.FindProcess(pid)
if err != nil {
return nil, fmt.Errorf("find pid %d: %s", pid, err)
}
return &osProcess{Process: proc}, nil
}
func (osp *osProcess) Wait() error {
if osp.finished {
return fmt.Errorf("already waited")
}
osp.finished = true
state, err := osp.Process.Wait()
if err != nil {
return err
}
if !state.Success() {
return &exec.ExitError{ProcessState: state}
}
return nil
}
func (osp *osProcess) String() string {
return fmt.Sprintf("pid=%d", osp.Pid)
}