user1075627
user1075627

Reputation: 51

Handling multiple signals

I have a question about handling a signal. Assume that if we receive SIGINT signal we should print "Received Signal". If within ten seconds the handler receives another signal it should print "Shutting Down" then exit with status 1.

I made my code like this:

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

void handler(int);
void secondhandler(int);
void alrmhandler(int);

void alrmhandler(int alrmsig) {
    alarm(0);
}

void secondhandler(int sig) {
    /* after recieving second signal prints shutting down and exit */
    printf("Shutting Down\n");
    exit(1);
}

void handler(int sig) {
    /* receive first SIGINT signal */
    printf("Received Signal\n");
    /* handle for the alarm function */
    signal(SIGALRM, alrmhandler);
    /* start 10s alarm */
    alarm(10);
    /* catch second SIGINT signal within 10s*/
    signal(SIGINT, secondhandler);
}

int main(void) {
    signal(SIGINT, handler);
    printf("Hello World!\n");
    for (;;) {
        /* infinite loop */
    }

    return 0;
}

I tried to compile it with Dev-C++, but it failed with SIGALRM was undeclared (first use in this function).

Anyway, what I want to know is if this code is right. I'm actually kinda not sure with the alrmhandler(). Should I ignore the SIGALRM?

Upvotes: 5

Views: 5343

Answers (2)

pilcrow
pilcrow

Reputation: 58589

You write:

what I want to know is if this code is right.

Not entirely. printf() is not async-signal-safe, and so should not be called from within a signal handler unless you are very sure it is safe to do so. It is not safe to do so within the code you provide.

The alarm() technique is, generally, race-prone. Your ten second alarm might expire in the middle of your secondhandler() function. To guard against this, you might mask out signals to compensate with a more sophisticated signal manipulation function.

There are more elegant/flexible ways of implementing the timeout you desire, but that's perhaps a question better suited for codereview.stackexchange.com.

Upvotes: 1

C&#233;dric Julien
C&#233;dric Julien

Reputation: 80771

If you are on a Windows platform, the only signals you will be able to send are : SIGABRT, SIGFPE, SIGILL, SIGINT, SIGSEGV, or SIGTERM.

Upvotes: 4

Related Questions