Thursday, 24 May 2018

Signal handler using signal() commad

Signal handler using signal() commad


Declaration:

  • Following is the declaration for signal() function.
    • #include <signal.h>
    • typedef void (*sighandler_t)(int);
    • sighandler_t signal(int signum, sighandler_t handler)
    • other declare
      • void (*signal(int sig, void (*func)(int)))(int)


DESCRIPTION:

  •  signal() sets the disposition of the signal signum to handler, which is either SIG_IGN, SIG_DFL, or the address of a programmer-defined function (a "signal handler").
  • sig − This is the signal number to which a handling function is set. The following are few important standard signal numbers.

Return Value

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

Program:

* Singal program by Velraj.K
   Check : http://velrajcoding.blogspot.in
*/

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

void sighandler(int);

int main()
{
    signal(SIGINT, sighandler);

    signal(SIGHUP, sighandler);
    while(1)
    {
        printf("Going to sleep for a second...\n");
        sleep(1);
    }
    return(0);
}
void sighandler(int signum)
{
    static int sighup = 0;

    printf("Caught signal %d, coming out...\n", signum);
    switch(signum)
    {
        case SIGHUP:
            printf("Vel instid eSIGUP.\n");
            if(sighup++ %2)
            {
                printf("Ignore the sigint \n");
                signal(SIGINT, SIG_IGN);
            }
            else
            {
                printf("set defalt to  int \n");
                signal(SIGINT, SIG_DFL);
            }
            break;
    }

//    exit(1);
}


Output:


   $./a.out
   Going to sleep for a second...
   Going to sleep for a second...
   Going to sleep for a second...
   Going to sleep for a second...
   ^CCaught signal 2, coming out...
  

Send the signal from Command prompt:
1. Need to know the signal number:
  • The signal number will be different for OS, as check in net they commonly mentioned SIGUSR1 value as 10 but in mips64 archetecture, we are getting SIGUSR1 value as 16.
  • To know the signal number, give "kill -l" command to get signal number:

EG: $ kill -l
 1) SIGHUP       2) SIGINT       3) SIGQUIT      4) SIGILL       5) SIGTRAP
 6) SIGABRT      7) SIGEMT       8) SIGFPE       9) SIGKILL     10) SIGBUS
11) SIGSEGV     12) SIGSYS      13) SIGPIPE     14) SIGALRM     15) SIGTERM
16) SIGUSR1     17) SIGUSR2  

  • To send signal use below:
  • kill -s 16 14517
     


No comments:

Post a Comment