【发布时间】:2017-06-16 05:13:07
【问题描述】:
我的目标是在从 NodeJS 应用程序生成一个分离的、未引用的子进程后执行一些代码。这是我的代码:
var child_options = {
cwd : prj
, env : {
PATH: cmd_directory
}
, detatched : true
, stdio : 'ignore'
};
//Spawn a child process with myapp with the options and command line params
child = spawn('myapp', params_array, child_options, function(err, stdout, stderr){
if (err) {
console.log("\t\tProblem executing myapp =>\n\t\t" + err);
} else {
console.log("\t\tLaunched myapp successfully!")
}
});
//Handle the child processes exiting. Maybe send an email?
child.on('exit', function(data) {
fs.writeFile(path.resolve("/Users/me/Desktop/myapp-child.log"), "Finished with child process!");
});
//Let the child process run in its own session without parent
child.unref();
因此,当子进程完成时,exit 处理程序中的函数似乎没有被执行。有什么办法可以在子进程退出后执行代码,即使它已分离并且在调用.unref() 方法时也是如此?
请注意,如果我将child_options 对象中的'stdio' 键值从'ignore' 更改为'inherit',则exit 处理程序会执行。
有什么想法吗?
更新第 1 部分
所以,我仍然无法弄清楚这一点。我回到 spawn 上的 NodeJS 文档,并注意到有关生成“长时间运行的进程”的示例。在一个示例中,他们将子进程的输出重定向到文件,而不是仅使用 'ignore' 来设置 'stdio' 选项。所以我更改了child_options 对象中的'stdio' 键,如下所示,但是我仍然无法执行'close' 或'exit' 事件中的代码:
var out_log = fs.openSync(path.resolve(os.tmpdir(), "stdout.log"), 'a'),
err_log = fs.openSync(path.resolve(os.tmpdir(), "stderr.log"), 'a');
var child_options = {
cwd : prj
, env : {
PATH: cmd_directory
}
, detatched : true
, stdio : ['ignore', out_log, err_log]
};
所以,stdout.log 文件确实从子进程中获取了标准输出——所以我知道它会被重定向。但是,close 或exit 事件中的代码仍然没有执行。然后我想我可以检测到对out_log 文件的写入何时完成,在这种情况下我可以在那个时候执行代码。但是,我无法弄清楚如何做到这一点。有什么建议吗?
【问题讨论】:
标签: node.js child-process