Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com
Answertopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions
Privacy Policy

  




 

 

24.4.1 Signal Handlers that Return

Handlers which return normally are usually used for signals such as SIGALRM and the I/O and interprocess communication signals. But a handler for SIGINT might also return normally after setting a flag that tells the program to exit at a convenient time.

It is not safe to return normally from the handler for a program error signal, because the behavior of the program when the handler function returns is not defined after a program error. See Program Error Signals.

Handlers that return normally must modify some global variable in order to have any effect. Typically, the variable is one that is examined periodically by the program during normal operation. Its data type should be sig_atomic_t for reasons described in Atomic Data Access.

Here is a simple example of such a program. It executes the body of the loop until it has noticed that a SIGALRM signal has arrived. This technique is useful because it allows the iteration in progress when the signal arrives to complete before the loop exits.

     #include <signal.h>
     #include <stdio.h>
     #include <stdlib.h>
     
     /* This flag controls termination of the main loop. */
     volatile sig_atomic_t keep_going = 1;
     
     /* The signal handler just clears the flag and re-enables itself. */
     void
     catch_alarm (int sig)
     {
       keep_going = 0;
       signal (sig, catch_alarm);
     }
     
     void
     do_stuff (void)
     {
       puts ("Doing stuff while waiting for alarm....");
     }
     
     int
     main (void)
     {
       /* Establish a handler for SIGALRM signals. */
       signal (SIGALRM, catch_alarm);
     
       /* Set an alarm to go off in a little while. */
       alarm (2);
     
       /* Check the flag once in a while to see when to quit. */
       while (keep_going)
         do_stuff ();
     
       return EXIT_SUCCESS;
     }

 
 
  Published under the terms of the GNU General Public License Design by Interspire