如何在Node.js中给终端的子进程控制?

时间:2015-07-16 20:51:18

标签: javascript node.js bash terminal child-process

我有一个从终端(node myapp.js)运行的Node应用程序。 这个应用程序产生一个子节点进程(通过child_process.fork)。

在那之后,我想退出父进程,并给终端的子进程控制。现在,当我退出父进程时,子进程只在后台运行,终端返回bash。我怎样才能让终端进入子进程,所以它不会回到bash?

1 个答案:

答案 0 :(得分:0)

在node.js文档中查看child_process.spawn以及options.detached。这样的事情可能就是你想要的:

const spawn = require('child_process').spawn;

const child = spawn(process.argv[0], ['child_program.js'], {
  detached: true,
  stdio: ['ignore']
});

child.unref(); //causes the parent's event loop to not include the child in its reference count, allowing the parent to exit independently of the child, unless there is an established IPC channel between the child and parent.

Node提供了child_process模块​​,该模块有以下三种主要方法来创建子进程。

  • exec - child_process.exec方法在shell / console中运行命令并缓冲输出。
  • spawn - child_process.spawn使用给定命令启动新进程
  • fork - child_process.fork方法是spawn()创建子进程的特例。