From 0ecd1d0b126f6cb1779c2055851954056563fab7 Mon Sep 17 00:00:00 2001 From: dnomd343 Date: Tue, 16 Aug 2022 16:07:09 +0800 Subject: [PATCH] update: sub process exit --- src/main.go | 31 ++++++++++++++++++++++++++++--- src/process.go | 25 +++++++++++++++++++------ 2 files changed, 47 insertions(+), 9 deletions(-) diff --git a/src/main.go b/src/main.go index a767ae1..36e176a 100644 --- a/src/main.go +++ b/src/main.go @@ -1,11 +1,15 @@ package main import ( + "fmt" log "github.com/sirupsen/logrus" + "syscall" + "time" ) var xray *Process var sleep *Process +var empty *Process var logLevel = "warning" @@ -22,6 +26,21 @@ var addOnInbounds []interface{} var assetFile = "/etc/xproxy/assets.tar.xz" +func exit() { + log.Warningf("Start exit process") + xray.disableProcess() + xray.sendSignal(syscall.SIGTERM) + //log.Infof("Send kill signal to process %s", xray.caption) + sleep.disableProcess() + sleep.sendSignal(syscall.SIGTERM) + empty.disableProcess() + empty.sendSignal(syscall.SIGTERM) + log.Info("Wait sub process exit") + for !(xray.done && sleep.done) { + } + log.Infof("Exit complete") +} + func main() { log.SetLevel(log.DebugLevel) log.Warning("XProxy start") @@ -32,12 +51,18 @@ func main() { sleep = newProcess("sleep", "1000") sleep.startProcess(true, true) - done := make(chan bool, 1) + //done := make(chan bool, 1) daemon(xray) daemon(sleep) - - <-done + daemon(empty) + + fmt.Println("start sleep...") + time.Sleep(10 * time.Second) + fmt.Println("wake up") + exit() + + //<-done //content, err := os.ReadFile("test.yml") //if err != nil { diff --git a/src/process.go b/src/process.go index ad9c2dd..6c322ac 100644 --- a/src/process.go +++ b/src/process.go @@ -8,6 +8,7 @@ import ( ) type Process struct { + done bool enable bool caption string command []string @@ -43,9 +44,11 @@ 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 to process %s error -> %v", signal, p.caption, err) + if p != nil { + err := p.process.Process.Signal(signal) + if err != nil { + log.Errorf("Send signal %v to process %s error -> %v", signal, p.caption, err) + } } } @@ -56,6 +59,12 @@ func (p *Process) waitProcess() { } } +func (p *Process) disableProcess() { + if p != nil { + p.enable = false + } +} + func daemonSub(sub *Process) { for sub.isProcessAlive() { sub.waitProcess() @@ -69,7 +78,11 @@ func daemonSub(sub *Process) { } func daemon(sub *Process) { - go func() { - daemonSub(sub) - }() + if sub != nil && sub.enable { + log.Infof("Start daemon of process %s", sub.caption) + go func() { + daemonSub(sub) + sub.done = true + }() + } }