doushichi3678
2017-09-22 15:03
浏览 40
已采纳

检测僵尸子进程

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!

图片转代码服务由CSDN问答提供 功能建议

我的golang程序启动了一个应该永远运行的服务程序,如下所示: \ n

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

我不想要 等待“服务”终止,因为它应该永远运行。 但是,如果服务以某个错误启动(例如,如果另一个实例已在运行,它将终止),则子进程将退出并变为僵尸。

我的问题是在cmd.Start( ),我可以以某种方式检测子进程是否仍在运行,而不是变成僵尸吗? 首选方式可能是:

 如果cmd.Process.IsZombie(){
 ... ... 
} 
    
 
 

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

即 我希望有一些方法可以获取(子)进程的状态,而无需等待其退出代码,或者“窥视”其状态代码而不会阻塞。

谢谢!

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dongwen5870 2017-10-12 02:58
    已采纳

    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.

    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • doumi7854 2017-09-22 15:30

    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
    }
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题