circu.js
    Preparing search index...
    • Registers a callback to be invoked when a specific Unix signal is received. The handler automatically unrefs the libuv handle, so it won't prevent process exit.

      Parameters

      • sigNum: number

        The numeric signal identifier to listen for. Use constants from the signals object.

      • handler: () => void

        The function to call when the signal is received. The function receives no arguments.

      Returns SignalHandler

      A SignalHandler object that can be used to manually close the signal listener.

      If the second argument is not a function.

      If the signal handle cannot be initialized.

      If the signal cannot be started (with system error code).

      import { signal, signals } from 'signals';

      // Example 1: Graceful shutdown with SIGINT (Ctrl+C)
      const sigintHandler = signal(signals.SIGINT, () => {
      console.log('\nReceived SIGINT. Performing graceful shutdown...');

      // Perform cleanup operations
      cleanupDatabaseConnections();
      saveState();

      // Close the handler
      sigintHandler.close();

      // Exit the application
      // In txiki.js: tjs.exit(0)
      // In other contexts: use appropriate exit method
      exit(0);
      });

      console.log('Press Ctrl+C to test signal handling');

      // Example 2: Daemon cleanup with SIGTERM
      const sigtermHandler = signal(signals.SIGTERM, () => {
      console.log('Received SIGTERM, performing graceful shutdown...');

      // Cleanup logic
      stopServer();
      sigtermHandler.close();
      exit(0);
      });

      // Example 3: Check which signal is being monitored
      console.log(`Monitoring signal: ${sigintHandler.signal}`); // "SIGINT"

      // Example 4: Multiple signals sharing one handler
      function handleShutdown() {
      console.log('Shutdown signal received');
      sigintHandler.close();
      sigtermHandler.close();
      exit(0);
      }

      signal(signals.SIGINT, handleShutdown);
      signal(signals.SIGTERM, handleShutdown);

      // Example 5: Temporary signal handler with auto-cleanup
      const tempHandler = signal(signals.SIGUSR1, () => {
      console.log('Received SIGUSR1');
      tempHandler.close(); // Close after first trigger
      });

      // Example 6: Cleanup on error
      try {
      const handler = signal(99999, () => {}); // Invalid signal
      } catch (error) {
      console.error(`Failed to register signal handler: ${error.message}`);
      }