【发布时间】:2014-03-29 12:56:32
【问题描述】:
例如,在 SIGINT 处理程序中,我需要等到所有子进程都完成。但是孩子的“关闭”事件可能有处理程序,它们本身可能执行异步操作,如外部通知。
所以我需要等到
- child.close 和
- child.close 处理程序已完成并且
- 在 child.close 处理程序中启动的异步操作已全部完成。
下面是简化的当前代码,它只知道第二个检查点。
var child_process = require('child_process');
var events = require('events');
var timers = require('timers');
var childRunning = false; // has child flag (counter in actual app)
// starting child
var child = child_process.spawn(process.cwd()+'/stub.js',{detached:true});
childRunning = true;
child.on('close',function(){childRunning=false}); //
// example close handler with async action inside
// actually there is a bunch of such handlers
child.on('close',function(){
console.log('child close handler triggered');
timers.setTimeout(function(){
console.log('close handler async action completed')
}, 2000);
});
process.on('SIGINT',function(){
console.log("Received SIGINT");
closeApp=function(){
console.log("readyToExit");
process.exit();
}
if (!childRunning) closeApp();
// in fact, i need here not this event, but
// 'all close handlers are done their job'
child.once('close',closeApp);
})
// actually there is a daemon app, so it does not stop by itself at all
在此示例中,通常您会看到“关闭处理程序异步操作已完成”消息,但如果您按 ctrl+c 则该消息将丢失。所以我需要以某种方式将其重写为 se
我正在尝试找到一种解决方案,使近距离处理程序尽可能简单。 我不知道如何命名这个案例,所以谷歌搜索没有帮助。
【问题讨论】:
标签: javascript node.js events asynchronous