From fc70d5b782067b7e170de7dfaad199147d851997 Mon Sep 17 00:00:00 2001 From: dnomd343 Date: Tue, 16 Aug 2022 14:41:22 +0800 Subject: [PATCH] feat: demo of Process class --- src/main.go | 12 ++++++++++-- src/process.go | 53 ++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 63 insertions(+), 2 deletions(-) create mode 100644 src/process.go diff --git a/src/main.go b/src/main.go index 307f9f7..0cbe729 100644 --- a/src/main.go +++ b/src/main.go @@ -1,6 +1,7 @@ package main import ( + "fmt" log "github.com/sirupsen/logrus" ) @@ -23,6 +24,13 @@ func main() { log.SetLevel(log.DebugLevel) log.Warning("XProxy start") + ls := newProcess("ls", "-al") + ls.startProcess(true, true) + + fmt.Println(ls.isProcessAlive()) + ls.waitProcess() + fmt.Println(ls.isProcessAlive()) + //content, err := os.ReadFile("test.yml") //if err != nil { // panic(err) @@ -30,8 +38,8 @@ func main() { //loadConfig(content) //loadProxy("/etc/xproxy/config", "/xproxy") - loadGeoIp("/xproxy/assets") - loadGeoSite("/xproxy/assets") + //loadGeoIp("/xproxy/assets") + //loadGeoSite("/xproxy/assets") // TODO: auto-update assets file (by cron command) //loadDns() diff --git a/src/process.go b/src/process.go new file mode 100644 index 0000000..3789b5a --- /dev/null +++ b/src/process.go @@ -0,0 +1,53 @@ +package main + +import ( + log "github.com/sirupsen/logrus" + "os" + "os/exec" + "syscall" +) + +type Process struct { + command []string + process *exec.Cmd +} + +func newProcess(command ...string) *Process { + process := new(Process) + process.command = command + log.Debugf("New process -> %v", command) + return process +} + +func (p *Process) startProcess(isStdout bool, isStderr bool) { + p.process = exec.Command(p.command[0], p.command[1:]...) + if isStdout { + p.process.Stdout = os.Stdout + } + if isStderr { + p.process.Stderr = os.Stderr + } + err := p.process.Start() + if err != nil { + log.Errorf("Failed to start %v -> %v", p.command, err) + } + log.Infof("Start process %v -> PID = %d", p.command, p.process.Process.Pid) +} + +func (p *Process) isProcessAlive() bool { + return p.process.ProcessState == nil +} + +func (p *Process) sendSignal(signal syscall.Signal) { + err := p.process.Process.Signal(signal) + if err != nil { + log.Errorf("Send signal %v error -> %v", signal, p.command) + } +} + +func (p *Process) waitProcess() { + err := p.process.Wait() + if err != nil { + log.Errorf("Wait process error -> %v", p.command) + } +}