Signals in PureScript

Here’s the translation of the Go code to PureScript, along with explanations in Markdown format suitable for Hugo:

Our program demonstrates how to handle signals in PureScript. Here’s the full source code:

module Main where

import Prelude

import Effect (Effect)
import Effect.Console (log)
import Effect.Aff (Aff, launchAff_)
import Effect.Aff.AVar (AVar, empty, put, take)
import Node.Process (onSignal, Signal(..))

main :: Effect Unit
main = launchAff_ do
  -- Create an AVar to act as a channel for signal notifications
  sigs <- empty

  -- Register the AVar to receive notifications for SIGINT and SIGTERM
  _ <- onSignal SIGINT (put sigs SIGINT)
  _ <- onSignal SIGTERM (put sigs SIGTERM)

  -- Create another AVar to act as a done signal
  done <- empty

  -- This Aff computation waits for a signal and then notifies the program to finish
  void $ launchAff_ do
    sig <- take sigs
    log ""
    log $ show sig
    put done unit

  log "awaiting signal"
  _ <- take done
  log "exiting"

PureScript’s signal handling works differently from Go’s. We use the Node.Process module to register signal handlers and Effect.Aff.AVar to create synchronization primitives similar to channels.

We create an AVar called sigs to receive signal notifications. We then use onSignal to register this AVar to receive notifications for SIGINT and SIGTERM.

We create another AVar called done to act as a synchronization point for program termination.

We launch an asynchronous computation that waits for a signal, prints it, and then notifies the program that it can finish.

The main program waits until it receives the done signal before exiting.

When we run this program, it will block waiting for a signal. By typing ctrl-C (which the terminal shows as ^C), we can send a SIGINT signal, causing the program to print SIGINT and then exit.

$ spago run
awaiting signal
^C
SIGINT
exiting

This example demonstrates how to handle signals in PureScript, allowing for graceful shutdown or custom signal handling in your applications.