Detect when parent process exits

为君一笑 提交于 2019-12-07 01:48:44

问题


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.


回答1:


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 )




回答2:


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

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



回答3:


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.




回答4:


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



来源:https://stackoverflow.com/questions/5541288/detect-when-parent-process-exits

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!