C signal()

The signal() function defined in the signal.h header file. It helps to handle the signals with a signal numbers.


void (*signal(int sig, void (*func)(int)))(int); #where sig should be in integer

 

signal() Parameters:

The signal() function takes a signal number and a function as its parameter. Some important standard signal numbers are.

  • SIGABRT :  Abnormal termination, such as is initiated by the function
  • SIGFPE : Erroneous arithmetic operation, such as zero divide or an operation resulting in overflow
  • SIGILL : Invalid function image, such as an illegal instruction.
  • SIGINT : Interactive attention signal. Generally generated by the application user.
  • SIGSEGV : Invalid access to storage − When a program tries to read or write outside the memory it is allocated for it.
  • SIGTERM : Termination request sent to program.

Following are the predefined functions

  • SIG_DFL : Default handling − The signal is handled by the default action for that particular signal.
  • SIG_IGN : Ignore Signal − The signal is ignored.
Parameter Description Required / Optional
sig   the signal number to which a handling function is set. Required
func This is a pointer to a function. This can be a function defined by the programmer Required

signal() Return Value

The signal()  function returns the previous signal handler value or SIG_ERR on error.

Input Return Value
if parameters value of the signal handler

Examples of signal() 

Example 1: Working of pow() function in C?


#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
int main () {
   signal(SIGINT, handler);

   while(1) {
      printf("Going to sleep for a second...\n");
      sleep(1); 
   }
   return(0);
}

void handler(int SNo) {
   printf("Caught signal %d, coming out...\n", SNo);
   exit(1);
}

Output:


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...

Example 2: How signal() function works in C?


#include <stdio.h>
#include <signal.h>
int main()
{
    signal(SIGINT, handle_sigint);
    while (1)
    {
        printf(“signal processing\n”);
        sleep(1);
    }
    return 0;
}

Output:


signal processing   
signal processing        
signal processing      
terminated