Signal Handling

On POSIX-compliant operating systems, signals are used to interrupt or terminate running processes. A process can react to specific signals by implementing signal handlers. For instance, an application may catch SIGINT to terminate when the user presses CTRL + C. Some signal numbers for FreeBSD are shown in table 1. See the FreeBSD man pages for a list of all signals.

Number Name Default Action Description
1 SIGHUP terminate process terminal line hang-up
2 SIGINT terminate process interrupt program
3 SIGQUIT create core image quit program
9 SIGKILL terminate process kill program
Table 1: Selection of signals on FreeBSD (source)

A signal handler is registered by calling the signal() routine. The signal number and the handler function must be passed as arguments:

! signal_test.f90
program signal_test
    external :: sigint_handler

    call signal(2, sigint_handler)
    call sleep(30)
end program signal_test

subroutine sigint_handler
    print '(a)', 'Process interrupted (SIGINT), exiting ...'
end subroutine sigint_handler

Press CTRL + C to send SIGINT to the Fortran program.