> ## Documentation Index
> Fetch the complete documentation index at: https://bun.ll1025.cn/llms.txt
> Use this file to discover all available pages before exploring further.

# 衍生子进程并通过 IPC 通信

使用 [`Bun.spawn()`](/runtime/child-process) 来衍生子进程。当衍生第二个 `bun` 进程时，可以在两个进程之间打开一个直接的进程间通信（IPC）通道。

<Note>
  要与 Node.js 进程通信，请在 `Bun.spawn` 中设置 `serialization: "json"`。使用 `process.execPath` 获取当前运行中的 `bun` 可执行文件的路径。
</Note>

```ts parent.ts icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
const child = Bun.spawn(["bun", "child.ts"], {
  ipc(message) {
    /**
     * 从子进程接收到的消息
     **/
  },
});
```

***

父进程通过返回的 `Subprocess` 实例上的 `.send()` 方法向子进程发送消息。`ipc` 处理函数也会将子进程作为第二个参数接收。

```ts parent.ts icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
const childProc = Bun.spawn(["bun", "child.ts"], {
  ipc(message, childProc) {
    /**
     * 从子进程接收到的消息
     **/
    childProc.send("回复子进程");
  },
});

childProc.send("我是你父亲"); // 父进程也可以向子进程发送消息
```

***

子进程通过 `process.send()` 向父进程发送消息，并通过 `process.on("message")` 接收消息。这与 Node.js 中 `child_process.fork()` 使用的 API 相同。

```ts child.ts icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
process.send("来自子进程的字符串消息");
process.send({ message: "来自子进程的对象消息" });

process.on("message", message => {
  // 打印来自父进程的消息
  console.log(message);
});
```

***

默认情况下，消息使用 JSC 的 `serialize` API 进行序列化，该 API 支持 [`structuredClone` 支持的所有内容](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm)，包括字符串、类型数组和对象。这不支持对象所有权的转移。

```ts child.ts icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
// 发送字符串
process.send("来自子进程的字符串消息");

// 发送对象
process.send({ message: "来自子进程的对象消息" });
```

***

参见 [子进程](/runtime/child-process)。
