【问题标题】:How to give child process control of the terminal, in Node.js?如何在 Node.js 中赋予终端的子进程控制权?
【发布时间】:2015-10-06 11:51:01
【问题描述】:

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

发生这种情况后,我想退出父进程,并将终端的控制权交给子进程。现在,当我退出父进程时,子进程只是在后台运行,终端返回 bash。如何将终端提供给子进程,使其不会返回 bash?

【问题讨论】:

  • 如果你想分叉子进程,然后立即作为父进程死亡并让子进程接管,我的问题是:为什么要分叉一个新进程?
  • 如果能够按功能分离我的进程,而不是将它们全部集中到一个进程中,这将很方便。它将允许增加模块化。

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


【解决方案1】:

查看 node.js 文档中的 child_process.spawnoptions.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/控制台中运行命令并缓冲输出。
  • spawn - child_process.spawn 使用给定命令启动新进程
  • fork - child_process.fork 方法是 spawn() 创建子进程的特例。

【讨论】:

    猜你喜欢
    • 2020-04-18
    • 1970-01-01
    • 2011-03-02
    • 1970-01-01
    • 1970-01-01
    • 2017-04-28
    • 1970-01-01
    • 1970-01-01
    • 2015-09-29
    相关资源
    最近更新 更多