Signals in Racket
Here’s the translation of the Go code to Racket, formatted in Markdown suitable for Hugo:
Our program will demonstrate how to handle signals in Racket. We’ll create a program that waits for a signal (like SIGINT or SIGTERM) and then gracefully shuts down.
#lang racket
(require racket/system)
(define (handle-signal sig)
(printf "\nReceived signal: ~a\n" sig)
(exit 0))
(define (main)
(printf "Awaiting signal...\n")
; Set up signal handlers
(handle-signals
(list signal/int signal/term)
handle-signal)
; Keep the program running
(let loop ()
(sleep 1)
(loop)))
(main)
In this Racket program:
We import the
racket/system
module, which provides functions for handling system signals.We define a
handle-signal
function that will be called when a signal is received. It prints the signal and exits the program.In the
main
function:- We print a message indicating that we’re waiting for a signal.
- We use
handle-signals
to set up handlers for SIGINT and SIGTERM. When either of these signals is received, ourhandle-signal
function will be called. - We enter an infinite loop to keep the program running until a signal is received.
Finally, we call the
main
function to start the program.
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 the signal received and then exit.
$ racket signals.rkt
Awaiting signal...
^C
Received signal: break
In Racket, we don’t need to explicitly create channels or use goroutines as in the original example. The handle-signals
function sets up the signal handling for us, and our handler function is called directly when a signal is received.
This example demonstrates how to handle system signals in Racket, allowing for graceful shutdown or other appropriate actions when certain signals are received.