Home > Software design >  Declaring more than one handler in the same struct sigaction?
Declaring more than one handler in the same struct sigaction?

Time:01-11

I don't understand why and how this can be possible, in set_handler before the loop start i set 2handlers in the same struct sigaction and works. This doesn't make sense to me, like i think that the correct way to use this is say sa->handler = h_int and then in another struct sigaction say: sb->sa_handler = h_quit. But using the same struct works too and i don't know how, i tried put in debugger and couldn't see nothing that makes senses, i tried declare this two handlers in main() and don't use set_handler but did not work so this get more confuse. And there is some way to do this without use this function set_handler? like do this in the main

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

static void set_handler(int sig, void (*handler)(int), struct sigaction *sa);
static void h_int(int sig);
static void h_quit(int sig);

int main(void)
{
    struct sigaction sa;

    memset(&sa, 0, sizeof(sa));
    set_handler(SIGINT, h_int, &sa);
    set_handler(SIGQUIT, h_quit, &sa);
    /* set_handler(SIGQUIT, SIG_IGN, &sa); */
    while(1)
    {
    }
}

static void set_handler(int sig, void (*handler)(int), struct sigaction *sa)
{
    sa->sa_handler = handler;
    sigaction(sig, sa, NULL);
}

static void h_int(int sig)
{
    (void)sig;
    printf("hi C c\n");
}

static void h_quit(int sig)
{
    (void)sig;
    printf("ok C \\");
}

CodePudding user response:

There's no problem. The kernel makes a copy of the relevant information from the structure when you call sigaction(). It does not rely on the structure you pass continuing to be valid after it returns control to your code.

CodePudding user response:

The copy of a struct sigaction whose address is passed to the sigaction function is not saved in any way. Once sigaction returns that copy of the struct may freely be used for something else.

If this wasn't the case, then you wouldn't be able to use a function like this:

void setup_signal()
{
    struct sigaction sa;
    memset(&sa, 0, sizeof(sa));
    sa.sa_handler = h_int;
    sigaction(SIGINT, &sa, NULL);
}

Since sa goes out of scope once the function returns. But because the contents of sa is only used to set up the signal handler, there is no problem.

  •  Tags:  
  • Related