I think fork
没有detached
选项。参考fork 的节点文档 https://nodejs.org/api/child_process.html#child_process_child_process_fork_modulepath_args_options.
如果你使用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);
});
兔子.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);
我认为当你使用叉子时IPC channel
是在父进程和子进程之间建立的。您可以尝试断开连接IPC channel
在退出父进程之前优雅地退出。我会尝试一下,如果有效的话会更新答案。
Update:
我已经更新了cli.js
and rabbit.js
让它按要求工作。诀窍是使用ipc
文件描述符在stdio
选项。这样你就可以从孩子那里与父母沟通。前三名fd
如果标记为 s 将是默认值null
。欲了解更多信息,请参阅stdio 选项文档 https://nodejs.org/api/child_process.html#child_process_options_stdio