【问题标题】:How can I kill a child process without the child process 'exit' event triggering?如何在不触发子进程“退出”事件的情况下杀死子进程?
【发布时间】:2019-03-08 07:21:15
【问题描述】:

我正在生成一个子进程:

child = spawn("childprocess", [], {
    detached: true
}

我正在观看“退出”事件:

child.on('exit', (code, signal) => {
    // Do stuff
}

当我的应用退出时,我正在使用 taskkill 杀死孩子(因为这是在 Windows 上运行的):

exec(`taskkill /PID ${child.pid} /F /T`, (error, stdout, stderr) => {
    // Do stuff
}

问题是,当进程被终止时,退出事件会触发(可以理解),但我不希望它发生。有没有办法删除事件监听器?或者在不触发事件的情况下终止进程?我试过child.removeListener('exit'),但没用(可能是因为它是一个匿名函数?)。

【问题讨论】:

  • 也许您可以使用 IPC 并要求该进程自行终止
  • @Vitim.us,我没想到。不理想,但如果归根结底,我会记住这一点。

标签: javascript node.js child-process


【解决方案1】:

我试过child.removeListener('exit'),但没用(可能是因为它是一个匿名函数?)。

函数是否有名字并不重要。您只需将相同的函数对象传递给removeListener(或off):

var handler = (code, signal) => {};
child.on('exit', handler);
child.off('exit', handler);

或致电child.removeAllListeners('exit');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-27
    • 1970-01-01
    • 1970-01-01
    • 2017-08-05
    相关资源
    最近更新 更多