开发者

Detect when parent process exits

开发者 https://www.devze.com 2023-02-22 03:41 出处:网络
I will have a parent process that is used to handle webserver restarts. It will signal the child to stop listening for new requests, the child will signal the parent that it has stopped listening, the

I will have a parent process that is used to handle webserver restarts. It will signal the child to stop listening for new requests, the child will signal the parent that it has stopped listening, then the parent will signal the new child that it can start listening. In this way, we can accomplish less than 100ms down time for a restart of that level (I have a zero-downtime grandchild restart also, but that is not always enough of a restart).

The service manager will kill the parent when it is time for shutdown. How can 开发者_运维知识库the child detect that the parent has ended?

The signals are sent using stdin and stdout of the child process. Perhaps I can detect the end of an stdin stream? I am hoping to avoid a polling interval. Also, I would like this to be a really quick detection if possible.


a simpler solution could be by registering for 'disconnect' in the child process

process.on('disconnect', function() {
  console.log('parent exited')
  process.exit();
});


This answer is just for providing an example of the node-ffi solution that entropo has proposed (above) (as mentioned it will work on linux):

this is the parent process, it is spawning the child and then exit after 5 seconds:

var spawn = require('child_process').spawn;
var node = spawn('node', [__dirname + '/child.js']);
setTimeout(function(){process.exit(0)}, 5000);

this is the child process (located in child.js)

var FFI = require('node-ffi');
var current = new FFI.Library(null, {"prctl": ["int32", ["int32", "uint32"]]})

//1: PR_SET_PDEATHSIG, 15: SIGTERM
var returned = current.prctl(1,15);

process.on('SIGTERM',function(){
        //do something interesting
        process.exit(1);
});

doNotExit = function (){
        return true;
};
setInterval(doNotExit, 500);

without the current.prctl(1,15) the child will run forever even if the parent is dying. Here it will be signaled with a SIGTERM which will be handled gracefully.


Could you just put an exit listener in the parent process that signals the children?

Edit:
You can also use node-ffi (Node Foreign Function Interface) to call ...
prctl(PR_SET_PDEATHSIG, SIGHUP);
... in Linux. ( man 2 prctl )


I start Node.JS from within a native OSX application as a background worker. To make node.js exit when the parent process which consumes node.js stdout dies/exits, I do the following:

// Watch parent exit when it dies

process.stdout.resume();
process.stdout.on('end', function() {
  process.exit();
});

Easy like that, but I'm not exactly sure if it's what you've been asking for ;-)

0

精彩评论

暂无评论...
验证码 换一张
取 消