如何杀死nodejs中的childprocess?

Dee*_*til 57 shell child-process node.js

使用shelljs创建了一个子进程

!/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);
Run Code Online (Sandbox Code Playgroud)

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

Mic*_*ang 71

如果您可以使用内置节点child_process.spawn,则可以向SIGINT子进程发送信号:

var proc = require('child_process').spawn('mongod');
proc.kill('SIGINT');
Run Code Online (Sandbox Code Playgroud)

这样做的好处是主进程应该在所有子进程终止之前一直存在.

  • 这是如何回答这个问题的?这个答案表明问题的作者已经采取了与杀死该过程完全相同的做法.然而它得到了许多赞成? (18认同)
  • @fishbone,不,这不一样。再读一遍。答案建议使用“spawn”而不是“exec”。 (5认同)
  • proc.kill() 还不够吗?或者我们需要 proc.kill('SIGINT') 吗? (4认同)
  • 错误的!您不能终止在子进程中启动的服务。您可以终止子进程但不能终止服务。这就是问题`传递给子进程的信号实际上可能不会终止进程。` https://nodejs.org/api/child_process.html#child_process_subprocess_kill_signal (2认同)
  • 谢谢,这节省了我的时间!另外,我遇​​到了一个问题,我的分叉进程产生了另一个进程(带有集群),并且 ```.kill('SIGINT')``` 成功了,并在我的电子 nodejs 应用程序中为我正确关闭了每个子进程和子进程 (2认同)