signal Function

Controls interrupt signal handling.

Include

<signal.h>

Prototype

void (*signal(int sig, void(*func)(int)))(int);

Arguments

sig signal name
func function to be executed

Return Value

Returns the previous value of func.

Example

#include <signal.h> /* for signal, raise, */
                    /* SIGINT, SIGILL, */
                    /* SIG_IGN, and SIGFPE */
#include <stdio.h>  /* for printf */

/* Signal handler function */
void mysigint(int id)
{
  printf("SIGINT received\n");
}

int main(void)
{
  /* Override default with user defined function */
  signal(SIGINT, mysigint);
  raise(SIGINT);

  /* Ignore signal handler */
  signal(SIGILL, SIG_IGN);
  raise(SIGILL);
  printf("SIGILL was ignored\n");

  /* Use default signal handler */
  raise(SIGFPE);
  printf("Program never reaches here.");
}

Example Output

SIGINT received
SIGILL was ignored
FPE

Example Explanation

The function mysigint is the user-defined signal handler for SIGINT. Inside the main program, the function signal is called to set up the signal handler (mysigint) for the signal SIGINT that will override the default actions. The function raise is called to report the signal SIGINT. This causes the signal handler for SIGINT to use the user-defined function (mysigint) as the signal handler so it prints the “SIGINT received” message.

Next, the function signal is called to set up the signal handler SIG_IGN for the signal SIGILL. The constant SIG_IGN is used to indicate the signal should be ignored. The function raise is called to report the signal SIGILL that is ignored.

The function raise is called again to report the signal SIGFPE. Since there is no user-defined function for SIGFPE, the default signal handler is used so the message “FPE” is printed (which stands for “arithmetic error - terminating”). Then, the calling program is terminated. The printf statement is never reached.