pankaj kushwaha pankaj kushwaha - 1 month ago 12
C Question

why my signal handler is not working using sigaction function?

I was trying following signal handler program , referring from an online tutorial , but it does not seems working , what is wrong with my code:

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

typedef void (*SignalHandlerPointer)(int);

static void UsrHostSigAbort(int pSignal)
{
//stopService();
printf("pankaj");
}
void HandleHostSignal()
{
struct sigaction satmp;
memset(&satmp, '\0' , sizeof(satmp));
SignalHandlerPointer usrSigHandler;
satmp.sa_flags &= ~SA_SIGINFO;
satmp.sa_handler = UsrHostSigAbort;
usrSigHandler = sigaction (SIGINT , &satmp, NULL);
}

void main()
{
HandleHostSignal();

while(1)
{
sleep(1);
}
}


I am compiling and running this program in ubuntu.

Answer

This code — which is basically only a trivial variant on your code — runs correctly on macOS Sierra 10.12.1:

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

static void UsrHostSigAbort(int pSignal)
{
    // stopService();
    // Using printf is not good - see: http://stackoverflow.com/questions/16891019/
    // It will suffice for this code, however.
    printf("pankaj %d\n", pSignal);
}

static void HandleHostSignal(void)
{
    struct sigaction satmp;
    sigemptyset(&satmp.sa_mask);
    satmp.sa_flags = 0;
    satmp.sa_handler = UsrHostSigAbort;
    sigaction(SIGINT, &satmp, NULL);
}

int main(void)
{
    HandleHostSignal();

    while (1)
    {
        sleep(1);
        putchar('.');
        fflush(stdout);
    }
}

Example output (program called sig19):

$ ./sig19
......^Cpankaj 2
.....^Cpankaj 2
....^Cpankaj 2
...^Cpankaj 2
..^Cpankaj 2
.^Cpankaj 2
..................^\Quit: 3
$

I used the quit key (^\ on my terminal) to stop the program.