Skip to main content
On this page

Handle OS signals

⚠️ Windows only supports listening for SIGINT and SIGBREAK as of Deno v1.23.

Concepts Jump to heading

Set up an OS signal listener Jump to heading

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:

add_signal_listener.ts
console.log("Press Ctrl-C to trigger a SIGINT signal");

Deno.addSignalListener("SIGINT", () => {
  console.log("interrupted!");
  Deno.exit();
});

// Add a timeout to prevent process exiting immediately.
setTimeout(() => {}, 5000);

Run with:

deno run add_signal_listener.ts

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

signal_listeners.ts
console.log("Press Ctrl-C to trigger a SIGINT signal");

const sigIntHandler = () => {
  console.log("interrupted!");
  Deno.exit();
};
Deno.addSignalListener("SIGINT", sigIntHandler);

// Add a timeout to prevent process exiting immediately.
setTimeout(() => {}, 5000);

// Stop listening for a signal after 1s.
setTimeout(() => {
  Deno.removeSignalListener("SIGINT", sigIntHandler);
}, 1000);

Run with:

deno run signal_listeners.ts

Help us make these docs great!

Did you find what you needed?

Privacy policy

Make a contribution

Deno's docs are open source. See something that's wrong or unclear? Submit a pull request:

Edit this page