本文介绍了如何在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:

使用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脚本中分离生成的子进程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 09:31