如何在 Node js 中保持分叉的子进程处于活动状态

Fan*_*ung 6 javascript rabbitmq node.js forever

我想创建一个像带有node的foreverjs一样运行的rabbitmq cli。它可以生成 child_process 并使其在后台运行,并且可以随时与 child_process 进行通信。我面临的问题是,当主 cli 程序退出时,child_process 似乎也停止运行,我尝试使用 detached:true 和 .unref() 进行分叉,但它不起作用。即使父调用者进程退出后,如何在后台运行子进程?

cli.js - 父级

const { fork, spawn } = require('child_process');
const options = {
  stdio: ['pipe', 'pipe', 'pipe', 'ipc'],
  slient:true,
  detached:true
};

child = fork('./rabbit.js', [], options)

child.on('message', message => {
  console.log('message from child:', message);
  child.send('Hi');
  // exit parent
  process.exit(0);
});

child.unref()
Run Code Online (Sandbox Code Playgroud)

rabbit.js - 如果子进程启动并运行,“i”应该继续递增

var i=0;
i++;
if (process.send) {
  process.send("Hello"+i);
}

process.on('message', message => {
  console.log('message from parent:', message);
});
Run Code Online (Sandbox Code Playgroud)

yas*_*nth 6

我认为fork没有detached选择。请参阅fork 的节点文档

如果您使用spawn,即使父级退出,子级也会继续运行。我对你的代码进行了一些修改以使用spawn.

cli.js

const { fork, spawn } = require('child_process');
const options = {
  slient:true,
  detached:true,
    stdio: [null, null, null, 'ipc']
};

child = spawn('node', ['rabbit.js'], options);
child.on('message', (data) => {
    console.log(data);
    child.unref();
    process.exit(0);
});
Run Code Online (Sandbox Code Playgroud)

兔子.js

var i=0;
i++;
process.send(i);
// this can be a http server or a connection to rabbitmq queue. Using setInterval for simplicity
setInterval(() => {
    console.log('yash');
}, 1000);
Run Code Online (Sandbox Code Playgroud)

我认为当你使用fork时,IPC channel父进程和子进程之间就建立了一个。IPC channel您可以在退出父进程之前尝试优雅地断开连接。我会尝试一下,如果有效的话会更新答案。

更新:

我已更新cli.jsrabbit.js使其按要求工作。技巧是ipc在选项中使用文件描述符stdio。这样你就可以从孩子那里与父母沟通。如果标记为 ,前三个fd将是默认值null。有关更多信息,请参阅stdio 选项文档