Signals in Pascal

Here’s the translation of the Go code to Pascal, formatted in Markdown suitable for Hugo:

Our program demonstrates how to handle signals in Pascal. It shows how to gracefully shut down a program when it receives certain signals, such as SIGTERM or SIGINT.

program SignalHandling;

uses
  SysUtils, Unix;

var
  SignalReceived: Boolean;

procedure SignalHandler(Signal: cint); cdecl;
begin
  WriteLn;
  WriteLn('Signal received: ', Signal);
  SignalReceived := True;
end;

begin
  SignalReceived := False;

  // Register the signal handler for SIGINT and SIGTERM
  FpSignal(SIGINT, @SignalHandler);
  FpSignal(SIGTERM, @SignalHandler);

  WriteLn('Awaiting signal');

  // Wait until a signal is received
  while not SignalReceived do
  begin
    Sleep(100);
  end;

  WriteLn('Exiting');
end.

In this Pascal program, we use the Unix unit to access signal-related functions. Here’s a breakdown of the code:

  1. We define a boolean variable SignalReceived to indicate when a signal has been received.

  2. The SignalHandler procedure is our custom signal handler. It prints the received signal and sets SignalReceived to True.

  3. In the main program, we register our SignalHandler for both SIGINT and SIGTERM using the FpSignal function.

  4. We then enter a loop that continues until a signal is received. The Sleep function is used to prevent the loop from consuming too much CPU.

  5. Once a signal is received and processed by our handler, the loop exits and the program terminates.

To run this program:

  1. Save the code in a file named SignalHandling.pas.

  2. Compile it using a Pascal compiler, for example with Free Pascal:

    $ fpc SignalHandling.pas
  3. Run the compiled program:

    $ ./SignalHandling
    Awaiting signal
  4. In another terminal, you can send a signal to the program using the kill command. For example, to send SIGINT:

    $ kill -SIGINT <PID>

    Replace <PID> with the actual process ID of the running program.

  5. The program will then output:

    Signal received: 2
    Exiting

This example demonstrates how to handle signals in Pascal, allowing for graceful shutdown or other custom behaviors when specific signals are received.