How do I write an async child reaper in Go?

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

How do I write an async child reaper in Go?

问题

我有一些类似这样的Go代码:

cmd := exec.Command(command)
//...
cmd.Run()
func reapChild(cmd) {
    sigc := make(chan os.Signal, 1)
    signal.Notify(sigc, syscall.SIGCHLD)
    go func() {
        my_signal := <-sigc
        log.Infof("appstore: reapChildren: 收到了SIGCHLD信号")
        cmd.Wait()
        signal.Stop(sigc)
    }()
}

这段代码用于回收特定生成的子进程,但我正在寻找一种更通用的方法。

有没有办法从my_signal中获取PID?我正在寻找类似于<sys/wait.h>中的pid_t wait(int *status)的功能,Go语言提供了一个名为Wait4的函数,它接受一个特定的PID。

英文:

I have some go code like this:

cmd = exec.Command(command)
//...
cmd.Run()
func reapChild(cmd) {
	sigc := make(chan os.Signal, 1)
	signal.Notify(sigc, syscall.SIGCHLD)
	go func() {
		my_signal := &lt;- sigc
		log.Infof(&quot;appstore: reapChildren: got a SIGCHLD signal&quot;)
		cmd.Wait()
		signal.Stop(sigc)
	}()
}

This reaps the process for a specific spawned child, but I'm looking
for something more generic.

Is there a way to get the PID off my_signal? I'm looking for something
like the <sys/wait.h> pid_t wait(int *status) -- golang provides a function
called Wait4 that takes a specific PID.

答案1

得分: 2

如你所说,Go的syscall包中有这个函数:

func Wait4(pid int, wstatus *WaitStatus, options int, rusage *Rusage) (wpid int, err error)

这个函数似乎适合你的需求。根据BSD的wait(2)手册页(请记住Go部分是在Mac上开发的!):

wait4()调用为需要等待特定子进程、需要子进程累积的资源利用统计信息或需要选项的程序提供了一个更通用的接口。其他的等待函数是使用wait4()实现的

通过传递正确的参数,你可以使用Wait4实现你想要的功能。例如,如果你不想等待特定的子进程:

如果pid为-1,则调用会等待任何子进程。

你可以在手册页中找到你需要的其他信息。

英文:

As you say, Go's syscall package has this function:

func Wait4(pid int, wstatus *WaitStatus, options int, rusage *Rusage) (wpid int, err error)

That seems to work for you. From the BSD man page for wait(2) (remember that Go was developed partly on Macs!):

> The wait4() call provides a more general interface for programs that
> need to wait for certain child processes, that need resource
> utilization statistics accumulated by child processes, or that
> require options. The other wait functions are implemented using
> wait4()
.

By passing the right arguments, you can achieve what you want with Wait4. For example, if you don't want to wait for a specific child:

> If pid is -1, the call waits for any child process.

You can find the rest of the information you need in the man page.

huangapple
  • 本文由 发表于 2014年6月11日 09:18:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/24153268.html
匿名

发表评论

匿名网友

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

确定