C library function - signal()



The C library function void (*signal(int sig, void (*func)(int)))(int) sets a function to handle signal ie. a signal handler with signal number sig


Following is the declaration for signal() function.

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


  • sig -- This is the signal number to which a handling function is set. Folloing are few important standard signal numbers:

SIGABRT(Signal Abort) Abnormal termination, such as is initiated by the function.
SIGFPE(Signal Floating-Point Exception) Erroneous arithmetic operation, such as zero divide or an operation resulting in overflow (not necessarily with a floating-point operation).
SIGILL(Signal Illegal Instruction) Invalid function image, such as an illegal instruction. This is generally due to a corruption in the code or to an attempt to execute data.
SIGINT(Signal Interrupt) Interactive attention signal. Generally generated by the application user.
SIGSEGV(Signal Segmentation Violation) Invalid access to storage: When a program tries to read or write outside the memory it is allocated for it.
SIGTERM(Signal Terminate) Termination request sent to program.
  • func -- This is a pointer to a function. This can be a function defined by the programmer or one of the following predefined functions:

SIG_DFLDefault handling: The signal is handled by the default action for that particular signal.
SIG_IGNIgnore Signal: The signal is ignored.

Return Value

This function returns the previous value of the signal handler, or SIG_ERR on error.


The following example shows the usage of signal() function.

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>

void sighandler(int);

int main()
   signal(SIGINT, sighandler);

      printf("Going to sleep for a second...\n");


void sighandler(int signum)
   printf("Caught signal %d, coming out...\n", signum);

Let us compile and run the above program, this will produce the following result and program will go in infinite loop. To come out of the program we used CTRL + C keys.

Going to sleep for a second...
Going to sleep for a second...
Going to sleep for a second...
Going to sleep for a second...
Going to sleep for a second...
Caught signal 2, coming out...