Search code examples
c

Enable a signal handler using sigaction in C


  struct sigaction psa;

I have enabled my signal handler in the main function as shown below:

    memset (&psa, 0, sizeof (psa));
    psa.sa_handler = pSigHandler;
    sigaction (SIGALRM, &psa, NULL);
    sigaction(SIGVTALRM, &psa, NULL);
    sigaction(SIGPROF, &psa, NULL);

My signal handler is like this:

static void pSigHandler(int signo){
    printf("Pareint signum: %d", signo);// debug
    switch (signo) {
        case SIGALRM:
            printf("P SIGALRM handler");//debug
            break;
        case SIGVTALRM:
            printf("P SIGVTALRM handler");//debug
            break;
        case SIGPROF:
            printf("P SIGPROF handler");//debug
            break;
        default: /*Should never get this case*/
            break;
    }
    return;
}

Now my question may be obvious to some people, why didn't I see the printed debug lines when I run this? In fact, nothing was printed. Thank you very much for helping me to understand this. I'm running it on Linux, used Eclipse to program.


Solution

  • #include <stdio.h>
    #include <signal.h>
    
    static void pSigHandler(int signo){
        switch (signo) {
                case SIGTSTP:
                printf("TSTP");
                fflush(stdout);
                break;
        }
    }
    
    int main(void)
    {
        struct sigaction psa;
        psa.sa_handler = pSigHandler;
        sigaction(SIGTSTP, &psa, NULL);
        for(;;) {}
        return 0;
    }
    

    Because you need to fflush(stdout)

    try with C-z

    I'm not even sure if it's safe to use stdio in a signal handler though.

    Update: http://bytes.com/topic/c/answers/440109-signal-handler-sigsegv

    According to that link, you should not do this.