检测僵尸子进程

My golang program starts a service program which is supposed to run forever, like this:

cmd := exec.Command("/path/to/service")
cmd.Start()

I do NOT want to wait for the termination of "service" because it is supposed to be running forever. However, if service starts with some error (e.g. it will terminate if another instance is already running), the child process will exit and become zombie.

My question is, after cmd.Start(), can I somehow detect if the child process is still running, rather than becomes a zombie? The preferred way might be:

if cmd.Process.IsZombie() {
    ... ...
}

or,

procStat := cmd.GetProcessStatus()
if procStat.Zombie == true {
    ... ...
}

i.e. I hope there are some way to get the status of a (child) process without waiting for its exit code, or, to "peek" its status code without blocking.

Thanks!

The best solution (for me) is:

  1. add a signal handler listen for SIGCHLD
  2. on receiving SIGCHLD, call cmd.Wait()

This way, the zombie process will disappear.

Judging from the docs the only way to get the process state is to call os.Process.Wait. So it seems you will have to call wait in a goroutine, and then you can easily check if that goroutine has exited yet:

var cmd exec.Cmd

done := make(chan error, 1)
go func() {
    done <- cmd.Wait()
}()

select {
case err := <-done:
    // inspect err to check if service exited normally
default:
    // not done yet
}