forked from codeskyblue/kexec
-
Notifications
You must be signed in to change notification settings - Fork 2
/
kexec.go
54 lines (49 loc) · 898 Bytes
/
kexec.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
package kexec
import (
"errors"
"os/exec"
"sync"
)
type KCommand struct {
*exec.Cmd
errCs []chan error
err error
finished bool
once sync.Once
mu sync.Mutex
}
func (c *KCommand) Run() error {
if err := c.Start(); err != nil {
return err
}
return c.Wait()
}
// This Wait wraps exec.Wait, but support multi call
func (k *KCommand) Wait() error {
if k.Process == nil {
return errors.New("exec: not started")
}
k.once.Do(func() {
if k.errCs == nil {
k.errCs = make([]chan error, 0)
}
go func() {
k.err = k.Cmd.Wait()
k.mu.Lock()
k.finished = true
for _, errC := range k.errCs {
errC <- k.err
}
k.mu.Unlock()
}()
})
k.mu.Lock()
if k.finished {
k.mu.Unlock()
return k.err
}
errC := make(chan error, 1)
k.errCs = append(k.errCs, errC)
k.mu.Unlock()
return <-errC
}