Multiple Signal Processing

I have a question about signal processing. Suppose that if we get a SIGINT signal, we should print “Received signal”. If within ten seconds the handler receives another signal, it should print “Shutdown” and then exit with status 1.

I made my code as follows:

#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 ) { /* recieve first SIGINT signal */ printf ("Recieved 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 that failed. Since SIGALRM is not declared (first used in this function).

In any case, I want to know if this code is correct. I am really not sure with alrmhandler (). Should I ignore SIGALRM?

+4
source share
2 answers

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

+3
source

You write:

I want to know if this code is correct.

Not really. printf () is not async-signal-safe and therefore should not be called from a signal handler unless you are sure that it is safe for this. It is not safe to do in the code that you provide.

The alarm () method is usually a race. Your ten second alarm may expire in the middle of your secondhandler () function. To prevent this, you can mask the signals to compensate for the more complex signal manipulation function .

There are more elegant / flexible ways to implement the timeout you desire, but this is a question that works best for codereview.stackexchange.com .

+1
source

Source: https://habr.com/ru/post/1384131/


All Articles