【问题标题】:How to terminate child process on node.js?如何终止 node.js 上的子进程?
【发布时间】:2016-11-28 11:37:21
【问题描述】:

我有几个节点的子进程,这取决于主进程。每个进程都是一个带有一些异步逻辑的程序。当一切都完成后,我必须终止这个过程。但是进程不会自己终止,导致有一些听众在上面。示例:

    if (cluster.isMaster) {

      for (var i = 0; i < numCPUs; i++) {
        let worker = cluster.fork();
        worker.send(i);
      }

   } else {
      process.once('message', msg => {
        // here some logic
        // and after this is done, process have to terminated
        console.log(msg);
      })
    }

但过程仍然有效,即使我使用“一次”。我曾尝试删除所有进程侦听器,但它仍然有效。我怎样才能终止它?

【问题讨论】:

  • 我不确定你在问什么,但一个好的旧 return; 不会终止回调吗?
  • 不,没有帮助

标签: node.js process


【解决方案1】:

像这样使用模块

终止

根据进程 ID 终止 Node.js 进程 一种基于进程 ID 终止 Node.js 进程 (and all Child Processes) 的简约但可靠(经过测试)的方法

var terminate = require('terminate');
terminate(process.pid, function(err, done){
  if(err) { // you will get an error if you did not supply a valid process.pid 
    console.log("Oopsy: " + err); // handle errors in your preferred way. 
  }
  else {
    console.log(done); // do what you do best! 
  }
});

我们可以使用 {detached: true} 选项启动子进程,这样这些进程就不会附加到主进程,而是会转到一组新的进程。然后在主进程上使用 process.kill(-pid) 方法,我们可以杀死具有相同 pid 组的子进程的同一组中的所有进程。就我而言,我在这个组中只有一个进程。

var spawn = require('child_process').spawn;

var child = spawn('my-command', {detached: true});

process.kill(-child.pid);

【讨论】:

    【解决方案2】:

    对于集群工作进程,可以调用process.disconnect()断开与主进程的IPC通道。连接 IPC 通道将使工作进程保持活动状态。

    【讨论】:

      猜你喜欢
      • 2014-06-30
      • 2022-01-20
      • 2021-12-05
      • 1970-01-01
      • 2011-01-21
      • 1970-01-01
      • 2023-03-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多