From 6b5b19ed27b16173ce383aef19b441b8786fed21 Mon Sep 17 00:00:00 2001 From: dnomd343 Date: Tue, 16 Aug 2022 15:45:07 +0800 Subject: [PATCH] feat: daemon feature --- src/main.go | 20 ++++++++++++++------ src/process.go | 32 +++++++++++++++++++++++++++----- 2 files changed, 41 insertions(+), 11 deletions(-) diff --git a/src/main.go b/src/main.go index 0cbe729..a767ae1 100644 --- a/src/main.go +++ b/src/main.go @@ -1,10 +1,12 @@ package main import ( - "fmt" log "github.com/sirupsen/logrus" ) +var xray *Process +var sleep *Process + var logLevel = "warning" var v4RouteTable = 100 @@ -24,12 +26,18 @@ func main() { log.SetLevel(log.DebugLevel) log.Warning("XProxy start") - ls := newProcess("ls", "-al") - ls.startProcess(true, true) + xray = newProcess("xray", "-confdir", "/etc/xproxy/config") + xray.startProcess(true, true) + + sleep = newProcess("sleep", "1000") + sleep.startProcess(true, true) + + done := make(chan bool, 1) + + daemon(xray) + daemon(sleep) - fmt.Println(ls.isProcessAlive()) - ls.waitProcess() - fmt.Println(ls.isProcessAlive()) + <-done //content, err := os.ReadFile("test.yml") //if err != nil { diff --git a/src/process.go b/src/process.go index 3789b5a..ad9c2dd 100644 --- a/src/process.go +++ b/src/process.go @@ -8,14 +8,18 @@ import ( ) type Process struct { + enable bool + caption string command []string process *exec.Cmd } func newProcess(command ...string) *Process { process := new(Process) + process.enable = true process.command = command - log.Debugf("New process -> %v", command) + process.caption = command[0] + log.Debugf("New process %s -> %v", process.caption, process.command) return process } @@ -29,9 +33,9 @@ func (p *Process) startProcess(isStdout bool, isStderr bool) { } err := p.process.Start() if err != nil { - log.Errorf("Failed to start %v -> %v", p.command, err) + log.Errorf("Failed to start %s -> %v", p.caption, err) } - log.Infof("Start process %v -> PID = %d", p.command, p.process.Process.Pid) + log.Infof("Start process %s -> PID = %d", p.caption, p.process.Process.Pid) } func (p *Process) isProcessAlive() bool { @@ -41,13 +45,31 @@ func (p *Process) isProcessAlive() bool { 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) + log.Errorf("Send signal %v to process %s error -> %v", signal, p.caption, err) } } func (p *Process) waitProcess() { err := p.process.Wait() if err != nil { - log.Errorf("Wait process error -> %v", p.command) + log.Warningf("Wait process %s -> %v", p.caption, err) } } + +func daemonSub(sub *Process) { + for sub.isProcessAlive() { + sub.waitProcess() + } + log.Warningf("Catch process %s exit", sub.caption) + if sub.enable { + sub.startProcess(true, true) + log.Infof("Process %s restart success", xray.caption) + daemonSub(sub) + } +} + +func daemon(sub *Process) { + go func() { + daemonSub(sub) + }() +}