signal()

Associates a signal handler with a signal.

  #include <signal.h> 
  void (*signal(int sig, void (*func)(int)))(int);   
Parameter

sig

A signal number.

func

A pointer to a signal handling function.

Remarks

The signal() function returns a pointer to a signal handling routine that takes an int value argument.

The sig argument is the signal number associated with the signal handling function. The signals defined in signal.h are listed in the table below.
Table 1. Signal Description
Macro Signal
SIGABRT Abort signal. Defined as a positive integer value. This signal is called by the abort()function.
SIGBREAK Terminates the calling program.
SIGFPE Floating point exception signal. Defined as a positive integer value.
SIGILL Illegal instruction signal. Defined as a positive integer value.
SIGINT Interactive user interrupt signal. Defined as a positive integer value.
SIGSEGV Segment violation signal. Defined as a positive integer value.
SIGTERM Terminal signal. Defined as a positive integer value. When raised this signal terminates the calling program by calling the exit()function.
The func argument is the signal handling function. This function is either programmer supplied or one of the pre-defined signal handlers listed in the table below.
Table 2. Signal-handling Functions
Function Action
SIG_IGN Nothing. It is used as a function argument in signal()to designate that a signal be ignored.
SIG_DFL Aborts the program by calling abort().
SIG_ERR Returned by signal()when it cannot honor a request passed to it.

When it is raised, a signal handler's execution is preceded by the invocation of signal(sig, SIG_DFL). This call to signal() disables the user's handler. It can be reinstalled by placing a call within the user handler to signal() with the user's handler as its function argument.

This function returns a pointer to the signal handling function set by the last call to signal() for signal sig. If the request cannot be honored, signal() returns SIG_ERR.

This facility may not be available on some configurations of the EWL.

Listing: Example of signal() usage

#include <signal.h> 
#include <stdio.h> 
#include <stdlib.h> 
void userhandler(int); 
void userhandler(int sig) 
{ 
char c; 
printf("userhandler!\nPress return.\n"); 
/* wait for the return key to be pressed */ 
c = getchar(); 
} 
int main(void) 
{ 
void (*handlerptr)(int); 
int i; 
handlerptr = signal(SIGINT, userhandler); 
if (handlerptr == SIG_ERR) 
printf("Can't assign signal handler.\n"); 
for (i = 0; i < 10; i++) { 
printf("%d\n", i); 
if (i == 5) 
raise(SIGINT); 
} 
return 0; 
} 
Output: 
0 
1 
2 
3 
4 
CodeWarrior Implementation of the C Standard Library 153 
5 
userhandler! 
Press return. 
6 
7 
8 
9