---
title: "共享内存"
description: "零拷贝访问客户机的 /dev/shm。"
---

> Documentation Index
> Fetch the complete documentation index at: https://unkernel.ndjp.net/llms.txt
> Use this file to discover all available pages before exploring further.

# 共享内存

```js
const vm = await createKernel({ shm: true });
await vm.exec("sh", ["-c", "printf result > /dev/shm/output"]);

const output = await vm.shm.open("output"); // 客户机程序创建的文件
const data = await output.read();
const views = output.views(); // 零拷贝，直到内核再次运行

const input = await vm.shm.create("input", 1 << 20); // 客户机中的 /dev/shm/input
await input.write(0, bytes);
```

客户机的 init 挂载 `/dev/shm` 之后它才存在，所以在 `create()` 之前要先等客户机就绪（`exec()` 会等）。

`openId(id)` 打开客户机程序经 `/dev/kwshm` 导出的 memfd。

`views()` 与 `readSync()` 只在 `vm.shm.inPlace` 为 true 时可用：`inline` 模式，以及带多个 CPU 和共享内存的 worker 模式（跨源隔离的页面、Node）。在其他情况下，`read()` 会跨到内核所在的 worker 取数据。

Source: https://unkernel.ndjp.net/sdk/shm/index.mdx
