tags:

views:

54

answers:

2

Hi,

I am trying to create a handler for the exit signal in c and my operating system is ubuntu.

I am using sigaction method to register my custom handler method.

int sigaction(int signum, const struct sigaction *act, struct sigaction *oldact);

Here's my code

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

void CustomHandler(int signo)
{
    printf("Inside custom handler");
    switch(signo)
    {
    case SIGFPE:
        printf("ERROR: Illegal arithmatic operation.\n");
        break;

    }

    exit(signo);
}

void newCustomHandler(int signo)
{
    printf("Inside new custom handler");
    switch(signo)
    {
    case SIGINT:
        printf("ERROR: Illegal arithmatic operation.\n");
        break;

    }

    exit(signo);
}

int main(void)
{
    long value;
    int i;
    struct sigaction act = {CustomHandler};
    struct sigaction newact = {newCustomHandler};


    newact = act;
    sigaction(SIGINT, &newact, NULL); //whats the difference between this

    /*sigaction(SIGINT, &act, NULL); // and this?
    sigaction(SIGINT, NULL, &newact);*/


    for(i = 0; i < 5; i++)
    {
        printf("Value: ");
        scanf("%ld", &value);
        printf("Result = %ld\n", 2520 / value);
    }
}

Now when I run the program and press Ctrl + c it displays Inside Inside custom handler.

I have read the documentation for sigaction and it says

If act is non-null, the new action for signal signum is installed from act. If oldact is non-null, the previous action is saved in oldact.

why do I need to pass the second structure when I can directly assign the values like

newact = act

Thanks.

+4  A: 

oldact is useful to reset the previous action handler:

sigaction(SIGINT, &copyInterrupted, &previousHandler);
copy(something);
sigaction(SIGINT, &previousHandler, null);

This way, you can reset the previous signal handler even if you do not know what it was.

Sjoerd
Sorry, I am a learner. Why do we need to reset previous signal handler? Can't we manually reset it? Or is it a extra feature?
Searock
@Searock the third line of code is resetting the previous handler.
manneorama
@manneorama thanks for the reply, but my main question why do I have to reset the previous handler using sigaction method? can't I reset it like a normal structure?
Searock
@Sjoerd thanks for your answer. Now I understand what you mean by "reset the previous signal handler even if you do not know what it was".
Searock
+1  A: 

When you call sigaction, you replace the old handler with the new one; the oldact pointer is set to point to the handler information in effect before this replacement.

Perhaps, as is often the case, you want the new handlers to be in effect for only a limited region of the code: now that you know what the configuration was before you changed it, you can restore it by another call to sigaction, at the end of this region.

Norman Gray
Sorry, I am a learner. Can you give me a example?
Searock