-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommand.go
67 lines (58 loc) · 1.67 KB
/
command.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
package main
import (
"errors"
"os"
"os/exec"
"strings"
"syscall"
)
// Command struct expressses background process that constructed by exec.Cmd
// If start Command, Command struct sends status to ReadyCh (error OR nil)
// If exit Command, Command struct sends status to ExitCh (error OR nil)
type Command struct {
ExecCmd *exec.Cmd
ReadyCh chan error
ExitCh chan error
}
// NewCommand crates new command instance with option
func NewCommand(cmdString string, readyCh chan error, exitCh chan error) (*Command, error) {
if cmdString == "" {
return nil, errors.New("command must be non empty value")
}
cmdSplit := strings.Fields(cmdString)
cmd := exec.Command(cmdSplit[0], cmdSplit[1:]...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
return &Command{
ExecCmd: cmd,
ReadyCh: readyCh,
ExitCh: exitCh,
}, nil
}
// HandleSignal function handles signal that sent through signalCh.
func (command *Command) HandleSignal(signalCh chan os.Signal) {
for sig := range signalCh {
// If command.ExecCmd.Process is running, command.ExecCmd.ProcessState = nil.
// After call command.ExecCmd.Process.Wait(), command.ExecCmd.ProcessState != nil
if command.ExecCmd.ProcessState == nil {
command.ExecCmd.Process.Signal(sig)
}
}
}
// Execute function Start and Wait command
// If exit by non signal cause, send error through ExitCh
func (command *Command) Execute() {
err := command.ExecCmd.Start()
command.ReadyCh <- err
err = command.ExecCmd.Wait()
if err != nil {
if exitError, ok := err.(*exec.ExitError); ok {
waitStatus := exitError.Sys().(syscall.WaitStatus)
if !waitStatus.Signaled() {
command.ExitCh <- err
return
}
}
}
command.ExitCh <- nil
}