Handle OS Signals

This program makes use of an unstable Deno feature. Learn more about unstable features.

Concepts

  • Use the --unstable flag to access new or unstable features in Deno.
  • Deno.signal can be used to capture and monitor OS signals.
  • Use the dispose() function of the Deno.signal SignalStream to stop watching the signal.

Async iterator example

You can use Deno.signal() function for handling OS signals:

  1. /**
  2. * async-iterator-signal.ts
  3. */
  4. console.log("Press Ctrl-C to trigger a SIGINT signal");
  5. for await (const _ of Deno.signal(Deno.Signal.SIGINT)) {
  6. console.log("interrupted!");
  7. Deno.exit();
  8. }

Run with:

  1. deno run --unstable async-iterator-signal.ts

Promise based example

Deno.signal() also works as a promise:

  1. /**
  2. * promise-signal.ts
  3. */
  4. console.log("Press Ctrl-C to trigger a SIGINT signal");
  5. await Deno.signal(Deno.Signal.SIGINT);
  6. console.log("interrupted!");
  7. Deno.exit();

Run with:

  1. deno run --unstable promise-signal.ts

Stop watching signals

If you want to stop watching the signal, you can use dispose() method of the signal object:

  1. /**
  2. * dispose-signal.ts
  3. */
  4. const sig = Deno.signal(Deno.Signal.SIGINT);
  5. setTimeout(() => {
  6. sig.dispose();
  7. console.log("No longer watching SIGINT signal");
  8. }, 5000);
  9. console.log("Watching SIGINT signals");
  10. for await (const _ of sig) {
  11. console.log("interrupted");
  12. }

Run with:

  1. deno run --unstable dispose-signal.ts

The above for-await loop exits after 5 seconds when sig.dispose() is called.