Files

75 lines
1.3 KiB
Go
Raw Permalink Normal View History

2020-09-15 19:52:54 -05:00
package process
import (
2021-02-06 21:50:21 +11:00
"os"
2020-09-15 19:52:54 -05:00
"os/exec"
)
// Process defines a process that can be executed
type Process struct {
cmd *exec.Cmd
exitChannel chan bool
Running bool
}
// NewProcess creates a new process struct
func NewProcess(cmd string, args ...string) *Process {
2021-02-06 21:50:21 +11:00
result := &Process{
2020-09-15 19:52:54 -05:00
cmd: exec.Command(cmd, args...),
exitChannel: make(chan bool, 1),
}
2021-02-06 21:50:21 +11:00
result.cmd.Stdout = os.Stdout
result.cmd.Stderr = os.Stderr
return result
2020-09-15 19:52:54 -05:00
}
// Start the process
func (p *Process) Start(exitCodeChannel chan int) error {
2020-09-15 19:52:54 -05:00
err := p.cmd.Start()
if err != nil {
return err
}
p.Running = true
go func(cmd *exec.Cmd, running *bool, exitChannel chan bool, exitCodeChannel chan int) {
err := cmd.Wait()
if err == nil {
exitCodeChannel <- 0
}
2020-09-15 19:52:54 -05:00
*running = false
exitChannel <- true
}(p.cmd, &p.Running, p.exitChannel, exitCodeChannel)
2020-09-15 19:52:54 -05:00
return nil
}
// Kill the process
func (p *Process) Kill() error {
if !p.Running {
return nil
}
err := p.cmd.Process.Kill()
2021-05-18 21:22:52 +10:00
if err != nil {
return err
}
err = p.cmd.Process.Release()
if err != nil {
return err
}
2020-09-15 19:52:54 -05:00
// Wait for command to exit properly
<-p.exitChannel
return err
}
// PID returns the process PID
func (p *Process) PID() int {
return p.cmd.Process.Pid
}
2021-10-03 22:19:40 +11:00
func (p *Process) SetDir(dir string) {
p.cmd.Dir = dir
}