当前位置: 代码迷 >> JavaScript >> 如何在Node.js中提供终端的子进程控制?
  详细解决方案

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

热度:12   发布时间:2023-06-12 14:04:01.0

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

在那之后,我想退出父进程,并赋予终端的子进程控制权。 现在,当我退出父进程时,子进程仅在后台运行,终端返回bash。 我如何才能将终端交给子进程,这样它就不会退回到bash?

看看child_process.spawn以及options.detached在Node.js的文档。 您可能正在寻找这样的东西:

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()创建子进程的特例。
  相关解决方案