-
Notifications
You must be signed in to change notification settings - Fork 29
/
gow_cmd.go
117 lines (97 loc) · 2.04 KB
/
gow_cmd.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
package main
import (
"errors"
"io"
"os"
"os/exec"
"sync"
"syscall"
"github.com/mitranim/gg"
)
type Cmd struct {
Mained
sync.Mutex
Buf [1]byte
Cmd *exec.Cmd
Stdin io.WriteCloser
}
func (self *Cmd) Deinit() {
defer gg.Lock(self).Unlock()
self.DeinitUnsync()
}
func (self *Cmd) DeinitUnsync() {
// Should kill the entire subprocess group.
self.BroadcastUnsync(syscall.SIGTERM)
self.Cmd = nil
self.Stdin = nil
}
func (self *Cmd) IsRunning() bool {
defer gg.Lock(self).Unlock()
return self.IsRunningUnsync()
}
func (self *Cmd) IsRunningUnsync() bool {
cmd := self.Cmd
return cmd != nil && cmd.ProcessState == nil
}
func (self *Cmd) Restart() {
defer gg.Lock(self).Unlock()
self.DeinitUnsync()
main := self.Main()
cmd := main.Opt.MakeCmd()
stdin, err := cmd.StdinPipe()
if err != nil {
log.Println(`unable to initialize subcommand stdin:`, err)
return
}
// Starting the subprocess populates its `.Process`,
// which allows us to kill the subprocess group on demand.
err = cmd.Start()
if err != nil {
log.Println(`unable to start subcommand:`, err)
return
}
self.Cmd = cmd
self.Stdin = stdin
go main.CmdWait(cmd)
}
func (self *Cmd) Broadcast(sig syscall.Signal) {
defer gg.Lock(self).Unlock()
self.BroadcastUnsync(sig)
}
/*
Sends the signal to the subprocess group, denoted by the negative sign on the
PID. Requires `syscall.SysProcAttr{Setpgid: true}`.
*/
func (self *Cmd) BroadcastUnsync(sig syscall.Signal) {
proc := self.ProcUnsync()
if proc != nil {
gg.Nop1(syscall.Kill(-proc.Pid, sig))
}
}
func (self *Cmd) WriteChar(char byte) {
// Locking and unlocking for every character might be wasteful.
// Might even be stupidly wasteful. TODO measure.
defer gg.Lock(self).Unlock()
stdin := self.Stdin
if stdin == nil {
return
}
buf := &self.Buf
buf[0] = char
_, err := stdin.Write(buf[:])
if err == nil {
return
}
if errors.Is(err, os.ErrClosed) {
self.Stdin = nil
return
}
panic(err)
}
func (self *Cmd) ProcUnsync() *os.Process {
cmd := self.Cmd
if cmd != nil {
return cmd.Process
}
return nil
}