Sunday, July 24, 2022

[SOLVED] What is the use of second structure(*oldact) in sigaction()

Issue

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.


Solution

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.



Answered By - Sjoerd
Answer Checked By - Marilyn (WPSolving Volunteer)