mirror of
https://github.com/pithings/unkernel.git
synced 2026-12-02 09:29:23 +08:00
46 lines
1.6 KiB
Markdown
46 lines
1.6 KiB
Markdown
---
|
|
icon: ph:terminal-window-duotone
|
|
---
|
|
|
|
# Run Programs
|
|
|
|
> Run guest programs on pipes or on their own pty.
|
|
|
|
## `exec()`
|
|
|
|
```js
|
|
const { stdout, exitCode } = await vm.exec("uname", ["-a"]);
|
|
const { stdout: sum } = await vm.exec("sha256sum", [], { input: "hello" });
|
|
```
|
|
|
|
`exec()` runs a program on pipes and resolves with `{ stdout, stderr, exitCode, signal }`, also for a non-zero exit. Pass `encoding: "buffer"` for bytes, and `cwd` or `env` as you would to `child_process`.
|
|
|
|
On the distro images programs run as the user `user` (uid 1000, in `/home/user`), who has `sudo` without a password. Pass `user: "root"` (or another name or uid) to run as someone else. The base shell is root's.
|
|
|
|
## `spawn()` on a pty
|
|
|
|
```js
|
|
const sh = await vm.spawn(); // a login shell on its own pty
|
|
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 })` runs a program on a pty, in the zigpty / node-pty shape, with `resize()`, `kill(signal)` and `close()` (a hangup). Run as many as you like.
|
|
|
|
::warning
|
|
Keep reading `output`: the guest program waits while nobody does.
|
|
::
|
|
|
|
## `spawn()` on pipes
|
|
|
|
```js
|
|
const gz = await vm.spawn("gzip", ["-c"], { pty: false });
|
|
gz.stderr.cancel(); // read both outputs, or cancel one
|
|
const zipped = new Response(gz.stdout).bytes();
|
|
await new Response("hello\n").body.pipeTo(gz.stdin); // then EOF
|
|
console.log((await zipped).length);
|
|
```
|
|
|
|
With `pty: false` the program gets pipes: `stdin`, `stdout` and `stderr` web streams, byte for byte.
|