Skip to main content
On this page

Handle OS signals

⚠️ Windows supports listening for SIGINT, SIGBREAK, SIGTERM, SIGQUIT, SIGHUP, and SIGWINCH (all except SIGINT/SIGBREAK go through libuv's Windows signal emulation).

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

Windows support Jump to heading

The supported signal set differs between platforms. The Windows-specific behavior is:

Use case Supported signals on Windows
Deno.addSignalListener(sig, …) SIGINT, SIGBREAK, SIGTERM, SIGQUIT, SIGHUP, SIGWINCH
Deno.kill(pid, sig) SIGINT, SIGBREAK, SIGTERM, SIGQUIT, SIGHUP, SIGWINCH, SIGKILL, SIGABRT, plus signal 0 for a process-health check

SIGKILL and SIGABRT are deliberately not registerable via addSignalListener — they're uncatchable / fatal, matching Unix semantics. On Windows the catchable signals all forward to libuv's emulation layer; signals sent via Deno.kill ultimately invoke TerminateProcess.

Last updated on

Did you find what you needed?

Privacy policy