C raise()

The raise() function defined in the signal.h header file. It helps to raise the signal specified in the argument and it will be compatible with the SIG macros. 

int raise(int sig); #where sig should be in integer

  

raise() Parameters: 

The raise() function takes a signal number 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.

 

Parameter Description Required / Optional
sig   the signal number to send Required

raise() Return Value

The raise()  function returns zero in the case of success and non-zero in failure. If the argument passed is not a valid signal then, the invalid parameter handler is invoked.

Input Return Value
if success zero
if failure non-zero

Examples of raise() 

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


#include <stdio.h>
#include <signal.h>
void signal_catchfunc(int);

int main () {
   int output;

   output = signal(SIGINT, signal_catchfunc);

   if( output == SIG_ERR) {
      printf("Error: unable to set signal handler.\n");
      exit(0);
   }
   printf("Signal is raising...\n");
   output = raise(SIGINT);
   
   if( output !=0 ) {
      printf("Error: unable to raise SIGINT signal.\n");
      exit(0);
   }

   printf("Going to Exit...\n");
   return(0);
}

void signal_catchfunc(int signal) {
   printf("! The is signal caught !\n");
}

Output:


Signal is raising...
! The is signal caught !
Going to Exit...

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


#include <stdio.h>
#include <signal.h>
void signal_handler(int sig)
{
    
    if (sig == SIGUSR1) printf("SIGUSR1 signal is Received..   \n");

    
    exit(0);
}

int main(int argc, const char * argv[])
{
    
    printf("Signal handler is registering..\n");

   
    signal(SIGUSR1, signal_handler);

    
    printf("SIGUSR1 signal is Raising..\n");

   
    raise(SIGUSR1);

   
    printf("Finished main\n");

    return 0;
}

Output:


Signal handler is registering..
SIGUSR1 signal is Raising..
SIGUSR1 signal is Received..