[英]How to detach a spawned child process in a Node.js script?
Intent: call an external application with specified arguments, and exit script. 意图:使用指定的参数调用外部应用程序,然后退出脚本。
The following script does not work as it should: 以下脚本不能正常工作:
#!/usr/bin/node
var cp = require('child_process');
var MANFILE='ALengthyNodeManual.pdf';
cp.spawn('gnome-open', ['\''+MANFILE+'\''], {detached: true});
Things tried: exec
- does not detach. 事情尝试:
exec
- 不分离。 Many thanks in advance 提前谢谢了
From node.js documentation: 从node.js文档:
By default, the parent will wait for the detached child to exit.
默认情况下,父级将等待已分离的子级退出。 To prevent the parent from waiting for a given child, use the child.unref() method, and the parent's event loop will not include the child in its reference count.
要防止父级等待给定的子级,请使用child.unref()方法,并且父级的事件循环不会将子级包含在其引用计数中。
When using the detached option to start a long-running process, the process will not stay running in the background unless it is provided with a stdio configuration that is not connected to the parent.
使用分离选项启动长时间运行的进程时,除非提供的stdio配置未连接到父进程,否则进程将不会在后台继续运行。 If the parent's stdio is inherited, the child will remain attached to the controlling terminal.
如果继承了父级的stdio,则子级将保持连接到控制终端。
You need to modify your code something like this: 您需要修改代码,如下所示:
#!/usr/bin/node
var fs = require('fs');
var out = fs.openSync('./out.log', 'a');
var err = fs.openSync('./out.log', 'a');
var cp = require('child_process');
var MANFILE='ALengthyNodeManual.pdf';
var child = cp.spawn('gnome-open', [MANFILE], { detached: true, stdio: [ 'ignore', out, err ] });
child.unref();
My solution to this problem: 我对这个问题的解决方案:
app.js app.js
require('./spawn.js')('node worker.js');
spawn.js spawn.js
module.exports = function( command ) {
require('child_process').fork('./spawner.js', [command]);
};
spawner.js spawner.js
require('child_process').exec(
'start cmd.exe @cmd /k "' + process.argv[2] + '"',
function(){}
);
process.abort(0);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.