简体   繁体   English

使用后如何杀死分叉的子进程?

[英]How do I kill forked child process after use?

I have this function and fork a child process to run a heavy work on background.我有这个功能并 fork 一个子进程在后台运行繁重的工作。 The work module sends message after it completes the work. work模块完成工作后发送消息。 How do I kill or close the forked process?如何终止或关闭分叉进程?

function doWork() {
    var child = cp.fork(__dirname + '/work');
    child.on('message', function(m) {
      console.log('completed: ' + m);
      // try to kill child process when work signals it's done
      child.kill('SIGHUP');
    });
    child.send({
      msg: 'do work',
      name: self.myname
    });
}

-edit- -编辑-

I tried child.kill('SIGHUP') and child.kill();我试过child.kill('SIGHUP')child.kill(); when work signals it's done.当工作信号完成时。 I seems didn't kill the process.我似乎没有杀死这个过程。 If I do ps | grep node如果我做ps | grep node ps | grep node , it still shows the work process is alive. ps | grep node ,它仍然显示工作进程是活动的。 What am I missing?我错过了什么?

I hope I'm not too late!我希望我不会太迟!

You can try to get pid of the forked child and pass it to child as reference and when job is done send pid along with the completion signal and you can kill the process based on pid.您可以尝试获取分叉子进程的 pid 并将其作为参考传递给子进程,当工作完成时,将 pid 与完成信号一起发送,您可以根据 pid 终止进程。

function doWork() {
    var child = cp.fork(__dirname + '/work');
    child.on('message', function(m) {
        //try to pass pid along with the signal from child to parent
        console.log('completed: ' + m);
        //killing child process when work signals it's done
        process.kill(m.pid);
    });
    child.send({
        msg: 'do work',
        name: self.myname,
        pid : child.pid // passing pid to child
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM