-
Notifications
You must be signed in to change notification settings - Fork 148
/
parent.go
80 lines (68 loc) · 1.55 KB
/
parent.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
package tableflip
import (
"encoding/gob"
"errors"
"fmt"
"io"
"io/ioutil"
"os"
)
const (
sentinelEnvVar = "TABLEFLIP_HAS_PARENT_7DIU3"
notifyReady = 42
)
type parent struct {
wr *os.File
result <-chan error
exited <-chan struct{}
}
func newParent(env *env) (*parent, map[fileName]*file, error) {
if env.getenv(sentinelEnvVar) == "" {
return nil, make(map[fileName]*file), nil
}
wr := env.newFile(3, "write")
rd := env.newFile(4, "read")
var names [][]string
dec := gob.NewDecoder(rd)
if err := dec.Decode(&names); err != nil {
return nil, nil, fmt.Errorf("can't decode names from parent process: %s", err)
}
files := make(map[fileName]*file)
for i, parts := range names {
var key fileName
copy(key[:], parts)
// Start at 5 to account for stdin, etc. and write
// and read pipes.
fd := 5 + i
env.closeOnExec(fd)
files[key] = &file{
env.newFile(uintptr(fd), key.String()),
uintptr(fd),
}
}
result := make(chan error, 1)
exited := make(chan struct{})
go func() {
defer rd.Close()
n, err := io.Copy(ioutil.Discard, rd)
if n != 0 {
err = errors.New("unexpected data from parent process")
} else if err != nil {
err = fmt.Errorf("unexpected error while waiting for parent to exit: %s", err)
}
result <- err
close(exited)
}()
return &parent{
wr: wr,
result: result,
exited: exited,
}, files, nil
}
func (ps *parent) sendReady() error {
defer ps.wr.Close()
if _, err := ps.wr.Write([]byte{notifyReady}); err != nil {
return fmt.Errorf("can't notify parent process: %s", err)
}
return nil
}