gpt4 book ai didi

node.js - 如何向使用 fork() 创建的子进程发送消息?

转载 作者:搜寻专家 更新时间:2023-10-31 23:52:37 24 4
gpt4 key购买 nike

我有一个父进程,它派生了一些子进程。我正在寻找子进程如何使用消息与父进程通信的某种方式。我尝试将父进程的 pid 发送到子进程,如果我可以使用父进程的 pid 发回消息,那就太好了。

提前致谢。

最佳答案

如果您使用 child_process.fork()然后当你创建一个新的 fork 时 Child Process被退回。

根据文档:

The returned ChildProcess will have an additional communication channel built-in that allows messages to be passed back and forth between the parent and child. See child.send() for details.

It is important to keep in mind that spawned Node.js child processes are independent of the parent with exception of the IPC communication channel that is established between the two. Each process has it's own memory, with their own V8 instances. Because of the additional resource allocations required, spawning a large number of child Node.js processes is not recommended.

这是 child.send 的文档

在哪里可以找到这段代码:

例如,在父脚本中:

const cp = require('child_process');
const n = cp.fork(`${__dirname}/sub.js`);

n.on('message', (m) => {
console.log('PARENT got message:', m);
});

n.send({ hello: 'world' });

然后子脚本“sub.js”可能如下所示:

process.on('message', (m) => {
console.log('CHILD got message:', m);
});

process.send({ foo: 'bar' });

关于node.js - 如何向使用 fork() 创建的子进程发送消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38184247/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com