1
0
mirror of https://github.com/fluencelabs/tendermint synced 2025-06-02 08:01:20 +00:00

76 lines
1.8 KiB
Go
Raw Normal View History

package process
import (
"fmt"
"io"
"os"
"os/exec"
"time"
)
type Process struct {
2015-04-10 02:12:17 -07:00
Label string
ExecPath string
2015-04-24 13:12:53 -07:00
Args []string
2015-04-16 09:46:35 -07:00
Pid int
2015-04-10 02:12:17 -07:00
StartTime time.Time
2015-04-16 09:46:35 -07:00
EndTime time.Time
2015-04-10 02:12:17 -07:00
Cmd *exec.Cmd `json:"-"`
ExitState *os.ProcessState `json:"-"`
2015-10-17 15:12:07 -07:00
InputFile io.Reader `json:"-"`
OutputFile io.WriteCloser `json:"-"`
2015-04-16 10:54:07 -07:00
WaitCh chan struct{} `json:"-"`
}
2015-04-08 11:35:17 -07:00
// execPath: command name
// args: args to command. (should not include name)
2015-10-17 15:12:07 -07:00
func Create(label string, execPath string, args []string, inFile io.Reader, outFile io.WriteCloser) (*Process, error) {
2015-04-08 11:35:17 -07:00
cmd := exec.Command(execPath, args...)
2015-10-17 15:12:07 -07:00
cmd.Stdout = outFile
cmd.Stderr = outFile
cmd.Stdin = inFile
if err := cmd.Start(); err != nil {
2015-04-16 09:46:35 -07:00
return nil, err
}
2015-04-16 09:46:35 -07:00
proc := &Process{
2015-04-10 02:12:17 -07:00
Label: label,
ExecPath: execPath,
2015-04-24 13:12:53 -07:00
Args: args,
2015-04-16 09:46:35 -07:00
Pid: cmd.Process.Pid,
2015-04-10 02:12:17 -07:00
StartTime: time.Now(),
Cmd: cmd,
ExitState: nil,
2015-10-17 15:12:07 -07:00
InputFile: inFile,
2015-04-10 02:12:17 -07:00
OutputFile: outFile,
2015-04-16 10:54:07 -07:00
WaitCh: make(chan struct{}),
}
2015-04-16 09:46:35 -07:00
go func() {
2015-04-16 10:54:07 -07:00
err := proc.Cmd.Wait()
if err != nil {
fmt.Printf("Process exit: %v\n", err)
if exitError, ok := err.(*exec.ExitError); ok {
proc.ExitState = exitError.ProcessState
}
}
2015-10-17 22:41:05 -07:00
proc.ExitState = proc.Cmd.ProcessState
2015-04-16 09:46:35 -07:00
proc.EndTime = time.Now() // TODO make this goroutine-safe
2015-05-30 17:30:25 -07:00
err = proc.OutputFile.Close()
if err != nil {
fmt.Printf("Error closing output file for %v: %v\n", proc.Label, err)
}
2015-04-16 10:54:07 -07:00
close(proc.WaitCh)
2015-04-16 09:46:35 -07:00
}()
return proc, nil
}
2015-04-08 11:35:17 -07:00
func Stop(proc *Process, kill bool) error {
defer proc.OutputFile.Close()
2015-04-08 11:35:17 -07:00
if kill {
2015-04-16 18:35:27 -07:00
fmt.Printf("Killing process %v\n", proc.Cmd.Process)
2015-04-08 11:35:17 -07:00
return proc.Cmd.Process.Kill()
} else {
2015-04-16 18:35:27 -07:00
fmt.Printf("Stopping process %v\n", proc.Cmd.Process)
2015-04-08 11:35:17 -07:00
return proc.Cmd.Process.Signal(os.Interrupt)
}
}