英文:
Child processes cleanup after termination
问题
我想在Go应用程序中运行另一个二进制文件,类似于以下方式:
cmd := exec.Command("another_app_binary", "-config", "config.conf")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Run()
当我终止父进程(上面的代码)时,子进程(another_app_binary)会变成孤儿进程。我有哪些选项可以在父进程退出/终止后清理子进程?它必须在Windows和Linux上都能正常工作。
英文:
I want to run another binary from go app with something like:
cmd := exec.Command("another_app_binary", "-config", "config.conf")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Run()
When I kill the parent process(code above), child process(another_app_binary) becomes orphan. What options do I have to cleanup child processes after parent exits/TERMINATES? It has to be somewhat platform nutural because I plan to run it on win/linux.
答案1
得分: 1
你可以使用os/signal包来监听当前进程中的终止信号。
import (
"os/exec"
"os"
"os/signal"
)
// ...
cmd := exec.Command("another_app_binary", "-config", "config.conf")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Run()
c := make(chan os.Signal, 2)
signal.Notify(c, os.Interrupt, os.Kill)
go func() {
<-c
// 清理操作
cmd.Process.Kill()
os.Exit(1)
}()
// ...
英文:
You can use the os/signal package to listen for the kill signal in your current process.
import (
"os/exec"
"os"
"os/signal"
)
// ...
cmd := exec.Command("another_app_binary", "-config", "config.conf")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Run()
c := make(chan os.Signal, 2)
signal.Notify(c, os.Interrupt, os.Kill)
go func() {
<-c
// cleanup
cmd.Process.Kill()
os.Exit(1)
}()
// ...
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论