Process management

Process signals and bounded restart policy

Graceful shutdown means stopping admission of new work, allowing appropriate in-flight work to finish within a deadline, and closing owned resources. A supervisor manages a process lifetime and can restart a failed process according to an explicit policy. On supported platforms, a SIGTERM handler can initiate shutdown. Registering a handler changes default signal behavior; ensure the handler eventually lets the process exit or enforces a deadline. For an HTTP service, stop accepting connections and drain active requests, then close dependencies. A second signal or an expired deadline may trigger forced cleanup; interruption can leave business effects incomplete, so use durable state and idempotency. Prefer setting exitCode and releasing handles over calling process.exit while output is pending. Restart budgets and backoff prevent crash loops; distinguish planned shutdown from failure. External supervisors such as systemd or PM2 are separate tools, not verified here. Do not keep accepting traffic during teardown, restart without bounds or signal unrelated PIDs. A liveness signal does not prove a worker is ready for requests. Test shutdown independently of startup. Sources: https://nodejs.org/download/release/v22.16.0/docs/api/process.html, https://nodejs.org/download/release/v22.16.0/docs/api/child_process.html.

Formal Syntax & Structure

nodejs syntaxnodejs
process.on(signal, listener); process.exitCode = integer

Working Example

Example Snippetnodejs
import {spawn} from 'node:child_process';import {once} from 'node:events';const child=spawn(process.execPath,['task.mjs'],{stdio:['ignore','pipe','pipe'],env:{LANG:'C.UTF-8'}});const done=once(child,'close');let output='';let signaled=false;child.stdout.setEncoding('utf8');child.stdout.on('data',chunk=>{output+=chunk;if(!signaled&&output.includes('ready\n')){signaled=true;child.kill('SIGTERM');}});child.stderr.resume();const timer=setTimeout(()=>child.kill('SIGKILL'),1500);try {const [code,signal]=await done;console.log(output.trim());console.log('exit',code,signal);}finally{clearTimeout(timer);if(child.exitCode===null&&child.signalCode===null)child.kill('SIGKILL');}
Node.js Reference