Signals in Co-array Fortran

Here’s the translation of the Go signals example to Co-array Fortran, formatted in Markdown suitable for Hugo:

program signals
  use, intrinsic :: iso_fortran_env
  use, intrinsic :: iso_c_binding
  implicit none

  integer :: ierr
  integer(c_int) :: sig
  type(c_funptr) :: old_handler
  logical :: done = .false.

  ! Register signal handlers
  call signal(SIGINT, handle_signal)
  call signal(SIGTERM, handle_signal)

  print *, "awaiting signal"

  ! Wait for signal
  do while (.not. done)
    call sleep(1)
  end do

  print *, "exiting"

contains

  subroutine handle_signal(sig) bind(c)
    integer(c_int), value :: sig
    print *
    print *, "Received signal:", sig
    done = .true.
  end subroutine handle_signal

end program signals

This program demonstrates how to handle signals in Co-array Fortran. Here’s a breakdown of the code:

  1. We use the iso_fortran_env and iso_c_binding modules for interoperability with C, which is necessary for signal handling.

  2. We declare variables for error handling, signal storage, and a flag to indicate when we’re done.

  3. The signal function is used to register our custom signal handler for SIGINT and SIGTERM.

  4. The main program enters a loop, waiting for a signal to be received.

  5. The handle_signal subroutine is our custom signal handler. It prints the received signal and sets the done flag to true.

  6. When a signal is received, the program exits the loop and terminates.

To run this program, save it as signals.f90 and compile it with a Fortran compiler that supports Co-array Fortran:

$ gfortran -fcoarray=single signals.f90 -o signals
$ ./signals
awaiting signal
^C
Received signal:           2
exiting

In this example, when we run the program, it blocks waiting for a signal. By typing ctrl-C, we send a SIGINT signal (which has a value of 2), causing the program to print the signal number and then exit.

Note that the exact behavior and available signals may vary depending on the operating system and Fortran implementation. Also, Co-array Fortran doesn’t have a direct equivalent to Go’s channels, so we’ve used a simple flag variable to communicate between the signal handler and the main program.