---
title: "运行程序"
description: "在管道或独立的 pty 上运行客户机程序。"
---

> 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.

# 运行程序

## `exec()`

```js
const { stdout, exitCode } = await vm.exec("uname", ["-a"]);
const { stdout: sum } = await vm.exec("sha256sum", [], { input: "hello" });
```

`exec()` 在管道上运行程序，以 `{ stdout, stderr, exitCode, signal }` resolve，退出码非零时也是如此。传入 `encoding: "buffer"` 可获得字节，`cwd` 和 `env` 的用法与传给 `child_process` 时相同。

在发行版镜像上，程序以用户 `user`（uid 1000，位于 `/home/user`）运行，该用户可以免密使用 `sudo`。传入 `user: "root"`（或其他用户名或 uid）可以换一个身份运行。基础 shell 以 root 运行。

## 在 pty 上 `spawn()`

```js
const sh = await vm.spawn(); // 一个运行在独立 pty 上的登录 shell
sh.output.pipeTo(new WritableStream({ write: (b) => process.stdout.write(b) }));
await sh.write("cat /etc/alpine-release; exit\n");
console.log(await sh.ended); // { type: "exit", code: 0 }
```

`spawn(file, args, { cols, rows })` 在 pty 上运行程序，接口形状与 zigpty / node-pty 一致，提供 `resize()`、`kill(signal)` 和 `close()`（挂断）。想开多少就开多少。

> **Caution**
>
> 持续读取 `output`：没人读的时候，客户机程序会等待。

## 在管道上 `spawn()`

```js
const gz = await vm.spawn("gzip", ["-c"], { pty: false });
gz.stderr.cancel(); // 读取两路输出，或取消其中一路
const zipped = new Response(gz.stdout).bytes();
await new Response("hello\n").body.pipeTo(gz.stdin); // 然后 EOF
console.log((await zipped).length);
```

用 `pty: false` 时，程序拿到的是管道：`stdin`、`stdout` 和 `stderr` 三个逐字节的 Web Streams。

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