Handle OS Signals

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

⚠️ Handling OS signals is currently not available on Windows.

Concepts

Set up an OS signal listener

APIs for handling OS signals are modelled after already familiar addEventListener and removeEventListener APIs.

⚠️ Note that listening for OS signals doesn’t prevent event loop from finishing, ie. if there are no more pending async operations the process will exit.

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

  1. /**
  2. * add_signal_listener.ts
  3. */
  4. console.log("Press Ctrl-C to trigger a SIGINT signal");
  5. Deno.addSignalListener("SIGINT", (_) => {
  6. console.log("interrupted!");
  7. Deno.exit();
  8. });
  9. // Add a timeout to prevent process existing immediately.
  10. setTimeout(() => {}, 5000);

Run with:

  1. deno run --unstable add_signal_listener.ts

You can use Deno.removeSignalListener() function to unregister previously added signal handler.

  1. /**
  2. * signal_listeners.ts
  3. */
  4. console.log("Press Ctrl-C to trigger a SIGINT signal");
  5. const sigIntHandler = (_) => {
  6. console.log("interrupted!");
  7. Deno.exit();
  8. };
  9. Deno.addSignalListener("SIGINT", sigIntHandler);
  10. // Add a timeout to prevent process existing immediately.
  11. setTimeout(() => {}, 5000);
  12. // Stop listening for a signal after 1s.
  13. setTimeout(() => {
  14. Deno.removeSignalListener("SIGINT", sigIntHandler);
  15. }, 1000);

Run with:

  1. deno run --unstable signal_listeners.ts

Async iterator example

If you prefer to handle signals using an async iterator, you can use signal() API available in deno_std:

  1. /**
  2. * async_iterator_signal.ts
  3. */
  4. import { signal } from "https://deno.land/std@$STD_VERSION/signal/mod.ts";
  5. const sig = signal("SIGUSR1", "SIGINT");
  6. // Add a timeout to prevent process existing immediately.
  7. setTimeout(() => {}, 5000);
  8. for await (const _ of sig) {
  9. console.log("interrupt or usr1 signal received");
  10. }

Run with:

  1. deno run --unstable async_iterator_signal.ts