开发者

Having trouble using sigaction with a timer signal

开发者 https://www.devze.com 2023-02-17 13:13 出处:网络
Hi everyone i\'m trying to use sigaction() however without success this is my code: int main() { struct sigaction act, oact;

Hi everyone i'm trying to use sigaction() however without success this is my code:

int main()
{

struct sigaction act, oact;
act.sa_handler = (void *)g;

sigaction(SIGVTALRM,&act,&oact);

struct itimerval tv;
tv.it_value.tv_sec = 2; //time of first timer
tv.it_value.tv_usec = 0; //time o开发者_C百科f first timer
tv.it_interval.tv_sec = 2; //time of all timers but the first one
tv.it_interval.tv_usec = 0; //time of all timers but the first one

setitimer(ITIMER_VIRTUAL, &tv, NULL);

for (;;);
}

this is g():

void g( void ){

    printf("I'M NOT IN G!!");
    for (;;);
}

when i run the code i get stuck in the first for(;;) loop without ever getting to g(). why don't i get to g() if i defined it as the function that handles the signal?

thank you


First, you should ensure that the input struct sigaction structure is clean:

sigemptyset(&act.sa_mask);
act.sa_flags = 0;
act.sa_handler = g;

Then, you should suspend the process rather than use a for-loop "spin wait":

sigset_t mask;
sigprocmask(0, NULL, &mask);
sigdelset(&mask, SIGVTALRM);
sigsuspend(&mask);

Lastly, your signal-handler should be defined correctly and not use the printf() function, which is considered unsafe in the presence of signals and shouldn't be used in a signal-handler. Instead, it should set an atomic flag:

static volatile sig_atomic_t g_called;

void g(int sig) {
    g_called = 1;
}


The fundamental problem is that you're using an uninitialized sigaction structure. Either initialize it with:

struct sigaction act = {0};

Or use memset to clear it before calling sigaction.

0

精彩评论

暂无评论...
验证码 换一张
取 消