如何派生另一个模块的进程 [英] How to fork a process of another module
问题描述
TL; DR:如何分叉当前运行进程之外的进程?
TL;DR : How does one fork a process that is located outside of the current running process?
我尝试使用Nodejs的 child_process
以便在父进程的出口退出时启动另一个nodejs进程。
I'm trying to use child_process
of Nodejs in order to start another nodejs process on the parent's process exit.
我使用 exec
成功执行了该过程,但是我需要子进程独立于父进程,因此父进程可以退出而无需等待子进程,因此我尝试使用 spawn
,其中 detached:true,stdio:'ignore'
选项和 unref()
进程:
I successfully executed the process with the exec
but I need the child process be independent of the parent, so the parent can exit without waiting for the child, hence I tried using spawn
with the detached: true, stdio: 'ignore'
option and unref()
ing the process:
设置options.detached为true使得子进程可以在运行后继续运行父级退出。
setting options.detached to true makes it possible for the child process to continue running after the parent exits.
spawn('node MY_PATH',[],{分离:true,stdio:' ignore'})。unref();
这将产生:
节点MY_PATH ENOENT
错误。
在使用 spawn
实现此操作并阅读文档再次,我认为我应该实际使用 fork
:
After having troubles achieving this with spawn
and reading the documentationagain i figured i should actually use fork
:
child_process.fork()方法是child_process.spawn()的特例,专门用于生成新的Node.js进程。
The child_process.fork() method is a special case of child_process.spawn() used specifically to spawn new Node.js processes.
fork()
并不将命令作为其第一个参数,但是 modulePath
我似乎不合适,因为我尝试作为子进程运行的脚本不在当前运行进程的目录中,而是依赖于
fork()
doesnt take a command as its' first argument, but a modulePath
which i can't seem to fit since the script I'm trying to run as a child process isnt in the directory of the current running process, but in a dependency of his.
回到起始TL; DR-如何分叉位于当前运行进程之外的进程?
Back to the starting TL;DR - how does one fork a process that is located outside of the current running process?
任何帮助将不胜感激!
编辑:
为 spawn
ENOENT错误提供解决方案也可能非常有帮助!
Providing a solution to the spawn
ENOENT error could be very helpfull too!
推荐答案
下面的代码应允许您执行所需的操作。
Following code should allow you to do what you need.
var Path = require('path');
var Spawn = require('child_process').spawn;
var relative_filename = '../../node_modules/bla/bla/bla.js';
Spawn('node', [Path.resolve(__dirname, relative_filename)], {detached: true, stdio: 'ignore'}).unref();
process.exit(0);
这篇关于如何派生另一个模块的进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!