子进程在终止后的清理工作

huangapple go评论95阅读模式
英文:

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 (
    &quot;os/exec&quot;
    &quot;os&quot;
    &quot;os/signal&quot;
)

// ...

cmd := exec.Command(&quot;another_app_binary&quot;, &quot;-config&quot;, &quot;config.conf&quot;)
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() {
	&lt;-c
    // cleanup
	cmd.Process.Kill()
	os.Exit(1)
}()

// ...

huangapple
  • 本文由 发表于 2017年4月14日 16:47:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/43408212.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定