Signals in Fortran
Our program demonstrates how to handle signals in Fortran. It will gracefully shut down when it receives a termination signal.
program signal_handler
use, intrinsic :: iso_c_binding, only: c_int, c_funptr
use, intrinsic :: iso_fortran_env, only: error_unit
implicit none
interface
function signal(signum, handler) bind(c)
import
integer(c_int), value :: signum
type(c_funptr), value :: handler
type(c_funptr) :: signal
end function signal
end interface
type(c_funptr) :: int_handler, term_handler
print *, "Awaiting signal"
int_handler = signal(2, c_funloc(handle_sigint))
term_handler = signal(15, c_funloc(handle_sigterm))
! Main program loop
do
call sleep(1)
end do
contains
subroutine handle_sigint() bind(c)
print *, "Interrupt signal received"
call exit(0)
end subroutine handle_sigint
subroutine handle_sigterm() bind(c)
print *, "Termination signal received"
call exit(0)
end subroutine handle_sigterm
end program signal_handlerIn Fortran, we use the signal function from the C library to set up signal handlers. We define two handler subroutines: one for the interrupt signal (SIGINT, usually triggered by Ctrl+C) and one for the termination signal (SIGTERM).
The program sets up these handlers and then enters an infinite loop, waiting for a signal. When a signal is received, the appropriate handler is called, which prints a message and exits the program.
To compile and run this program:
$ gfortran -o signal_handler signal_handler.f90
$ ./signal_handler
Awaiting signal
^C
Interrupt signal receivedIn this example, we use Ctrl+C to send an interrupt signal, causing the program to print “Interrupt signal received” and then exit.
Note that Fortran doesn’t have built-in support for channels or goroutines like Go does. Instead, we use a more traditional approach with signal handlers. The concept of graceful shutdown remains the same, but the implementation details differ due to the language’s features and idiomatic practices.
Comments powered by Disqus