如何杀死 nodejs 中的子进程?

使用 shell 创建一个子进程

!/usr/bin/env node


require('/usr/local/lib/node_modules/shelljs/global');
fs = require("fs");
var child=exec("sudo mongod &",{async:true,silent:true});


function on_exit(){
console.log('Process Exit');
child.kill("SIGINT");
process.exit(0)
}


process.on('SIGINT',on_exit);
process.on('exit',on_exit);

杀死父进程后,子进程仍在运行

100329 次浏览

If you can use node's built in child_process.spawn, you're able to send a SIGINT signal to the child process:

var proc = require('child_process').spawn('mongod');
proc.kill('SIGINT');

An upside to this is that the main process should hang around until all of the child processes have terminated.

// only windows


const module_child_process = require('child_process');
let proc = module_child_process.spawn("cmd");
let pid = proc.pid;
let cmd = `wmic process where parentprocessid=${pid} get ProcessId`;
let out = module_child_process.execSync(cmd);
let stdout = out.toString();
let pids=[];
let lines = stdout.split("\n");
for (let i = 0; i < lines.length; i++)
{
try
{
let data = lines[i].toString();
let val = parseInt(data.trim());
if (!isNaN(val))
{
//console.log(val.toString());
pids.push(val);
}
}
catch (ex)
{
}
}


for (let i = 0; i < pids.length; i++)
{
module_process.kill(pids[i]);
/* or
let cmd = `taskkill /pid ${pids[i].toString()} /T /F`;
console.log(cmd);
module_child_process.execSync(cmd);
*/
}


proc.kill();
proc = null;