Signals in Scala

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

Our first example demonstrates how to handle Unix signals in Scala. We’ll create a program that gracefully handles interruption signals.

import scala.concurrent.{Future, ExecutionContext}
import scala.concurrent.duration._
import sun.misc.{Signal, SignalHandler}

object SignalHandling extends App {
  // We'll use a Future to simulate a long-running process
  implicit val ec: ExecutionContext = ExecutionContext.global

  // Create a Promise to handle the completion of our program
  val done = scala.concurrent.Promise[Boolean]()

  // Set up our signal handler
  val handler = new SignalHandler {
    def handle(signal: Signal): Unit = {
      println()
      println(s"Received signal: ${signal.getName}")
      done.success(true)
    }
  }

  // Register our handler for SIGINT and SIGTERM
  Signal.handle(new Signal("INT"), handler)
  Signal.handle(new Signal("TERM"), handler)

  println("Awaiting signal...")

  // Simulate some work
  Future {
    while (!done.isCompleted) {
      Thread.sleep(100)
    }
  }

  // Wait for the signal
  scala.concurrent.Await.result(done.future, Duration.Inf)
  println("Exiting")
}

In this Scala program:

  1. We import necessary libraries for handling concurrent operations and signals.

  2. We create a Future to simulate a long-running process.

  3. We use a Promise to handle the completion of our program.

  4. We define a SignalHandler that prints the received signal and completes the Promise.

  5. We register our handler for SIGINT and SIGTERM signals.

  6. We start a Future that simulates work until the Promise is completed.

  7. Finally, we wait for the Promise to be completed (i.e., a signal to be received) before exiting.

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

$ scala SignalHandling.scala
Awaiting signal...
^C
Received signal: INT
Exiting

This example demonstrates how to handle signals in Scala, allowing for graceful shutdown of long-running processes when interruption signals are received.