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

# 派生子进程并使用 IPC 通信

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

<Note>
  此 API 仅与其他 `bun` 进程兼容。使用 `process.execPath` 可获取当前正在运行的
  `bun` 可执行文件的路径。
</Note>

```ts parent.ts icon="https://mintcdn.com/bun-zhcndoc/cnUTwgMuf4cCrwC-/icons/typescript.svg?fit=max&auto=format&n=cnUTwgMuf4cCrwC-&q=85&s=e7767043c9e885c34f2d6c8fe2a95217" theme={"theme":{"light":"github-light","dark":"dracula"}}
const child = Bun.spawn(["bun", "child.ts"], {
  ipc(message) {
    /**
     * 从子进程接收到的消息
     **/
  },
});
```

***

父进程可以使用返回的 `Subprocess` 实例上的 `.send()` 方法向子进程发送消息。在 `ipc` 处理器的第二个参数中，还可以获得发送消息的子进程的引用。

```ts parent.ts icon="https://mintcdn.com/bun-zhcndoc/cnUTwgMuf4cCrwC-/icons/typescript.svg?fit=max&auto=format&n=cnUTwgMuf4cCrwC-&q=85&s=e7767043c9e885c34f2d6c8fe2a95217" theme={"theme":{"light":"github-light","dark":"dracula"}}
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/bun-zhcndoc/cnUTwgMuf4cCrwC-/icons/typescript.svg?fit=max&auto=format&n=cnUTwgMuf4cCrwC-&q=85&s=e7767043c9e885c34f2d6c8fe2a95217" theme={"theme":{"light":"github-light","dark":"dracula"}}
process.send("来自子进程的字符串消息");
process.send({ message: "来自子进程的对象消息" });

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

***

所有消息均使用 JSC 的 `serialize` API 进行序列化，该 API 支持与 `postMessage` 和 `structuredClone` 相同的一组[可传输类型](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Transferable_objects)，包括字符串、类型化数组、流和对象。

```ts child.ts icon="https://mintcdn.com/bun-zhcndoc/cnUTwgMuf4cCrwC-/icons/typescript.svg?fit=max&auto=format&n=cnUTwgMuf4cCrwC-&q=85&s=e7767043c9e885c34f2d6c8fe2a95217" theme={"theme":{"light":"github-light","dark":"dracula"}}
// 发送字符串
process.send("来自子进程的字符串消息");

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

***

完整文档请参见 [Docs > API > 子进程](/runtime/child-process)。
