Translations of this page?:

signal

Syntax:

    #include <csignal>
    void ( *signal( int signal, void (* func) (int)) ) (int);

The signal() function sets func to be called when signal is received by your program. func can be a custom signal handler, or one of these macros (defined in the csignal header file):

MacroExplanation
SIG_DFLdefault signal handling
SIG_IGNignore the signal

Some basic signals that you can attach a signal handler to are:

SignalDescription
SIGTERMGeneric stop signal that can be caught.
SIGINTInterrupt program, normally ctrl-c.
SIGQUITInterrupt program, similar to SIGINT.
SIGKILLStops the program. Cannot be caught.
SIGHUPReports a disconnected terminal.
SIGSEGVReports a memory segmentation fault.

The return value of signal() is the address of the previously defined function for this signal, or SIG_ERR if there is an error.

For example, the following example uses the signal() function to call an arbitrary number of functions when the user aborts the program. The functions are stored in a vector, and a single “clean-up” function calls each function in that vector of functions when the program is aborted:

  void f1() {
    cout << "calling f1()..." << endl;
  }
 
  void f2() {
    cout << "calling f2()..." << endl;
  }
 
  typedef void(*endFunc)(void);
  vector<endFunc> endFuncs;
 
  void cleanUp( int dummy ) {
    for( unsigned int i = 0; i < endFuncs.size(); i++ ) {
      endFunc f = endFuncs.at(i);
      (*f)();
    }
    exit(-1);
  }
 
  int main() {
 
    // connect various signals to our clean-up function
    signal( SIGTERM, cleanUp );
    signal( SIGINT, cleanUp );
    signal( SIGQUIT, cleanUp );
    signal( SIGHUP, cleanUp );
 
    // add two specific clean-up functions to a list of functions
    endFuncs.push_back( f1 );
    endFuncs.push_back( f2 );
 
    // loop until the user breaks
    while( 1 );
 
    return 0;
  }

Related Topics: raise

 
• • • IndexRecent changesRSScc