11

I have this function and fork a child process to run a heavy work on background. The work module sends message after it completes the work. How do I kill or close the forked process?

function doWork() {
    var child = cp.fork(__dirname + '/work');
    child.on('message', function(m) {
      console.log('completed: ' + m);
      // try to kill child process when work signals it's done
      child.kill('SIGHUP');
    });
    child.send({
      msg: 'do work',
      name: self.myname
    });
}

-edit-

I tried child.kill('SIGHUP') and child.kill(); when work signals it's done. I seems didn't kill the process. If I do ps | grep node, it still shows the work process is alive. What am I missing?

codereviewanskquestions
  • 13,460
  • 29
  • 98
  • 167
  • 5
    Right in [the doc](https://nodejs.org/api/child_process.html#child_process_child_kill_signal) `child.kill()`. – jfriend00 Jan 21 '17 at 08:51
  • 2
    I tried that but it seems not working. when I do `child.kill()` and check if process is killed by `ps | grep node` and I still see the work process is alive – codereviewanskquestions Jan 22 '17 at 00:14
  • 1
    It depends upon your process and what signals it may be catching and handling on its own, but you may want to send it `child.kill('SIGKILL')` or `child.kill('SIGTERM')`. – jfriend00 Jan 22 '17 at 00:48
  • Possible duplicate of [How to kill childprocess in nodejs?](http://stackoverflow.com/questions/20187184/how-to-kill-childprocess-in-nodejs) – Paul Sweatte Jan 24 '17 at 22:51
  • 1
    @PaulSweatte Probably not, this is specific to a 'forked' child which behaves differently than other children. I am also having this issue. – Steven Rogers Oct 15 '18 at 14:08
  • I guess, you need to kill sub-process too. There are some packages available eg treekill. – Pankaj Tanwar Jul 16 '21 at 07:52

1 Answers1

1

I hope I'm not too late!

You can try to get pid of the forked child and pass it to child as reference and when job is done send pid along with the completion signal and you can kill the process based on pid.

function doWork() {
    var child = cp.fork(__dirname + '/work');
    child.on('message', function(m) {
        //try to pass pid along with the signal from child to parent
        console.log('completed: ' + m);
        //killing child process when work signals it's done
        process.kill(m.pid);
    });
    child.send({
        msg: 'do work',
        name: self.myname,
        pid : child.pid // passing pid to child
    });
}
Spoorthy
  • 17
  • 3