0
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2024-10-31 09:14:20 -04:00
denoland-deno/docs/examples/os_signals.md

84 lines
1.7 KiB
Markdown
Raw Normal View History

2020-09-12 08:03:18 -04:00
# Handle OS Signals
2020-05-06 18:21:13 -04:00
> This program makes use of an unstable Deno feature. Learn more about
> [unstable features](../runtime/stability.md).
2020-05-06 18:21:13 -04:00
2020-09-12 08:03:18 -04:00
## Concepts
- Use the `--unstable` flag to access new or unstable features in Deno.
2020-09-12 08:03:18 -04:00
- [Deno.signal](https://doc.deno.land/builtin/unstable#Deno.signal) can be used
to capture and monitor OS signals.
2020-09-12 08:03:18 -04:00
- Use the `dispose()` function of the Deno.signal
[SignalStream](https://doc.deno.land/builtin/unstable#Deno.SignalStream) to
stop watching the signal.
2020-09-12 08:03:18 -04:00
## Async iterator example
2020-05-06 18:21:13 -04:00
2020-08-15 09:46:36 -04:00
You can use `Deno.signal()` function for handling OS signals:
2020-05-06 18:21:13 -04:00
```ts
2020-09-12 08:03:18 -04:00
/**
* async-iterator-signal.ts
*/
console.log("Press Ctrl-C to trigger a SIGINT signal");
2020-05-06 18:21:13 -04:00
for await (const _ of Deno.signal(Deno.Signal.SIGINT)) {
console.log("interrupted!");
2020-09-12 08:03:18 -04:00
Deno.exit();
2020-05-06 18:21:13 -04:00
}
```
2020-09-12 08:03:18 -04:00
Run with:
```shell
deno run --unstable async-iterator-signal.ts
```
## Promise based example
2020-08-15 09:46:36 -04:00
`Deno.signal()` also works as a promise:
2020-05-06 18:21:13 -04:00
```ts
2020-09-12 08:03:18 -04:00
/**
* promise-signal.ts
*/
console.log("Press Ctrl-C to trigger a SIGINT signal");
await Deno.signal(Deno.Signal.SIGINT);
2020-05-06 18:21:13 -04:00
console.log("interrupted!");
2020-09-12 08:03:18 -04:00
Deno.exit();
2020-05-06 18:21:13 -04:00
```
2020-09-12 08:03:18 -04:00
Run with:
```shell
deno run --unstable promise-signal.ts
```
## Stop watching signals
2020-05-06 18:21:13 -04:00
If you want to stop watching the signal, you can use `dispose()` method of the
2020-08-15 09:46:36 -04:00
signal object:
2020-05-06 18:21:13 -04:00
```ts
2020-09-12 08:03:18 -04:00
/**
* dispose-signal.ts
*/
2020-05-06 18:21:13 -04:00
const sig = Deno.signal(Deno.Signal.SIGINT);
setTimeout(() => {
sig.dispose();
2020-09-12 08:03:18 -04:00
console.log("No longer watching SIGINT signal");
}, 5000);
2020-05-06 18:21:13 -04:00
2020-09-12 08:03:18 -04:00
console.log("Watching SIGINT signals");
2020-05-06 18:21:13 -04:00
for await (const _ of sig) {
console.log("interrupted");
}
```
2020-09-12 08:03:18 -04:00
Run with:
```shell
deno run --unstable dispose-signal.ts
```
2020-08-15 09:46:36 -04:00
The above for-await loop exits after 5 seconds when `sig.dispose()` is called.