简体   繁体   English

子进程不会被Node.JS杀死

[英]Child process not getting killed with Node.JS

I used child_process.exec / child_process.spawn to fork a new process and then kill it using child.kill / process.kill . 我使用child_process.exec / child_process.spawn来分叉一个新进程,然后使用child.kill / process.killchild.kill It works fine with simple binary executables, such as cat / ls , and the child process just get killed. 它可以很好地处理简单的二进制可执行文件,例如cat / ls ,并且子进程就会被杀死。

However, when get to the scripts (say P1) that forks another child process (say P2) , only the script interpreter P1 get killed, not the child process P2. 然而,当到达脚本(比如P1)叉另一个子进程(比如P2),仅脚本解释P1被打死,而不是子进程P2。

QUESTION : is there any way that getting such child process P2 killed with Node.JS? 问题 :有没有办法让Node.JS杀死这样的子进程P2?

Code works fine with run_and_kill('ls -Al /usr/lib') , but not OK with run_and_kill('firefox') : 使用run_and_kill('ls -Al /usr/lib')代码可以正常工作,但使用run_and_kill('firefox')

function run_and_kill(cmd) {
    var exec = require('child_process').exec,
        ls = exec(cmd);
    console.log('Child process started: %d', ls.pid);
    ls.on('exit', function(code, signal) {
        console.log('exit with code %s and signal %s', code, signal);
    });
    ls.kill();
}

The safest way I've found to achieve this is creating a spawn process to kill the signal, using the child.pid as argument. 我发现实现这一目标的最安全的方法是使用child.pid作为参数创建一个生成进程以终止信号。 Example with fork : fork示例:

var process;
process = require('child_process');

var fork, child;
fork = process.fork;
child = fork('./index');

var spawn;
spawn = process.spawn;
spawn('kill', [child.pid]);
console.log('sending SIGTERM to child process (socket server)');

I typically use this in specs, mostly in beforeAll/afterAll blocks to start/kill servers (in the example './index.js'). 我通常在规范中使用它,主要是在beforeAll / afterAll块中启动/终止服务器(在示例'./index.js'中)。

I think your P2 is neither a fork or a child of P1 but rather a parallel process spawned by it. 我认为你的P2不是P1的分叉或子代,而是由它产生的并行过程。 In the case of Firefox ( at least in Linux ) the firefox app is launched by a wrapper shell script. 对于Firefox(至少在Linux中),firefox应用程序由包装器shell脚本启动。 If it's always going to be firefox, better run the binary straight from it's install folder 如果它总是成为firefox,那么最好直接从它的安装文件夹中运行二进制文件

In my case the problem was the shell being used for the process. 在我的情况下,问题是用于进程的shell。 By default it's /bin/sh , and when this was being used it wasn't handling the kill signals. 默认情况下它是/bin/sh ,当使用它时它没有处理终止信号。

To fix this you can use /bin/bash instead: 要解决此问题,您可以使用/bin/bash代替:

exec('your command', {
    shell: '/bin/bash',
});

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

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