Skip to content

Child process does not get killed when parent dies by SIGKILL #1790

Closed
@surajwy

Description

@surajwy
  • Node.js Version: v8.12.0
  • OS: Mac, CentOS
  • Scope: runtime
  • Module:child_process.js and cluster.js

I create a child process using child_process.fork() method. When I kill parent using kill -9, the child does not die.
Now, If I use the cluster module to create a child process and kill the parent process with -9 signal, all the child dies. Even the cluster modules use child_process.fork() method internally.

So, what is the difference here? Shouldn't OS take care of sending SIGKILL to all children?

CODE

Case 1: Using child_process.fork()
parent.js

const { fork } = require('child_process');

const forked = fork('child.js');

forked.on('message', (msg) => {
        console.log('Message from child', msg);
});

forked.send({ hello: 'world' });

child.js

process.on('message', (msg) => {
        console.log('Message from parent:', msg);
});
let counter = 0;
setInterval(() => {
        try{
              process.send({ counter: counter++ });
        }
        catch(ex){
             // This will come once parent dies. 
             // One way can be to check for error code ERR_IPC_CHANNEL_CLOSED
             //     and call process.exit()
             console.log('parent died', ex.toString());
        }
    }, 1000);

Case 2: Using the cluster module
index.js

let cluster = require("cluster");

if (cluster.isMaster) {
    console.log('cluster settings', cluster.settings);
    cluster.fork();
    console.log('cluster settings', cluster.settings);
    cluster.on('fork', function (worker) {
        console.log('Worker ' + worker.process.pid + ' forked.');
    });
    cluster.on('exit', function (worker) {
        console.log('worker ' + worker.process.pid + ' died. Replacing the died worker...');
        cluster.fork();
    });
}
else {
    setInterval(() => {
        console.log('inside child')
    }, 5000)
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions