Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enable a signal handler using sigaction in C

Tags:

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.

like image 603
txs Avatar asked Feb 25 '11 04:02

txs


People also ask

Does sigaction call the signal handler?

sigaction() can be called with a NULL second argument to query the current signal handler. It can also be used to check whether a given signal is valid for the current machine by calling it with NULL second and third arguments.

What does sigaction return in C?

sigaction(sig, act, oact) means “set the disposition for sig to act , and store the old disposition in oact ”. Its return value is 0 or -1, indicating whether the system call errored.

What is signal sigaction?

The sigaction() function examines, changes, or both examines and changes the action associated with a specific signal. The sig argument must be one of the macros defined in the <signal. h> header file. If sigaction() fails, the action for the signal sig is not changed.

What is a handler function in C?

A signal handler is just a function that you compile together with the rest of the program. Instead of directly invoking the function, you use signal or sigaction to tell the operating system to call it when a signal arrives. This is known as establishing the handler.


1 Answers

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

like image 96
Thomas Dignan Avatar answered Oct 17 '22 11:10

Thomas Dignan