2

I have a few child processes of node, that depends from master. Every process is a program with some asynchronic logic. And i have to terminate this process when all will be done. But process not terminate by himself, cause there some listeners on it. Example:

    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);
      })
    }

But process still working, even i using "once". I had tried to remove all of process listeners, but it still works. How i can terminate it?

Jim Moriarty
  • 133
  • 1
  • 4

2 Answers2

2

Use module like

terminate

Terminate a Node.js Process based on the Process ID A minimalist yet reliable (tested) way to Terminate a Node.js Process (and all Child Processes) based on the Process ID

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! 
  }
});

or

We can start child processes with {detached: true} option so those processes will not be attached to main process but they will go to a new group of processes. Then using process.kill(-pid) method on main process we can kill all processes that are in the same group of a child process with the same pid group. In my case, I only have one processes in this group.

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

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

process.kill(-child.pid);
Adiii
  • 54,482
  • 7
  • 145
  • 148
0

For cluster worker processes, you can call process.disconnect() to disconnect the IPC channel with the master process. Having the IPC channel connected will keep the worker process alive.

mscdex
  • 104,356
  • 15
  • 192
  • 153