如何在Node.js脚本中分离生成的子进程? [英] How to detach a spawned child process in a Node.js script?

查看:79
本文介绍了如何在Node.js脚本中分离生成的子进程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

意图:使用指定的参数调用外部应用程序,然后退出脚本.

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

尝试过的事情:exec-不分离.提前非常感谢

Things tried: exec - does not detach. Many thanks in advance

推荐答案

来自node.js文档:

From node.js documentation:

默认情况下,父级将等待分离的子级退出.为了防止父级等待给定的子级,请使用child.unref()方法,并且父级的事件循环将其引用计数中不包括该子级.

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.

使用detached选项启动长时间运行的进程时,除非该进程提供了未连接到父级的stdio配置,否则该进程将不会在后台运行.如果父代的stdio被继承,则子代将保持与控制终端的连接.

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. If the parent's stdio is inherited, the child will remain attached to the controlling terminal.

您需要修改代码,如下所示:

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

这篇关于如何在Node.js脚本中分离生成的子进程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆