/
context.go
76 lines (65 loc) · 1.42 KB
/
context.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
package process
import (
"strings"
"syscall"
"github.com/hack-pad/hackpad/internal/fs"
"github.com/hack-pad/hackpad/internal/log"
)
const initialDirectory = "/home/me"
var (
currentPID PID
switchedContextListener func(newPID, parentPID PID)
)
func Init(switchedContext func(PID, PID)) {
// create 'init' process
fileDescriptors, err := fs.NewStdFileDescriptors(minPID, initialDirectory)
if err != nil {
panic(err)
}
p, err := newWithCurrent(
&process{fileDescriptors: fileDescriptors},
minPID,
"",
nil,
&ProcAttr{Env: splitEnvPairs(syscall.Environ())},
)
if err != nil {
panic(err)
}
p.state = stateRunning
pids[minPID] = p
switchedContextListener = switchedContext
switchContext(minPID)
}
func switchContext(pid PID) (prev PID) {
prev = currentPID
log.Debug("Switching context from PID ", prev, " to ", pid)
if pid == prev {
return
}
newProcess := pids[pid]
currentPID = pid
switchedContextListener(pid, newProcess.parentPID)
return
}
func Current() Process {
process, _ := Get(currentPID)
return process
}
func Get(pid PID) (process Process, ok bool) {
p, ok := pids[pid]
return p, ok
}
func splitEnvPairs(pairs []string) map[string]string {
env := make(map[string]string)
for _, pair := range pairs {
equalIndex := strings.IndexRune(pair, '=')
if equalIndex == -1 {
env[pair] = ""
} else {
key, value := pair[:equalIndex], pair[equalIndex+1:]
env[key] = value
}
}
return env
}