Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I kill forked child process after use?

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?

like image 595
codereviewanskquestions Avatar asked Jan 21 '17 08:01

codereviewanskquestions


People also ask

How do you end a child process in Nodejs?

kill('SIGINT');

Does killing parent process kill child process?

Killing a parent doesn't kill the child processes Every process has a parent. We can observe this with pstree or the ps utility. The ps command displays the PID (id of the process), and the PPID (parent ID of the process).

How do you get out of a child?

To finish a child process, the exit() system call is used in the child process. The wait() function is defined in the header sys/wait. h and the exit() function is defined in the header stdlib.

Can a process kill other process?

Either parent or child can signal the other, and in fact each signal can kill the other process.


1 Answers

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
    });
}
like image 107
Spoorthy Avatar answered Sep 28 '22 08:09

Spoorthy