C <signal.h> - signal() Function
The C <signal.h> signal() function is used to specify a way to handle the signal specified by sig. The parameter handler specifies the way in which a signal can be handled by a program. This must be one of the following:
- SIG_DFL: (Default handling) The signal is handled by the default action for that particular signal.
- SIG_IGN: (Ignore signal) The signal is ignored and the code execution will continue even if not meaningful.
- Function handler: A specific function is defined to handle the signal.
Either SIG_DFL or SIG_IGN is set as the default signal handling behavior at program startup for each of the supported signals.
Syntax
void (*signal( int sig, void (*handler) (int))) (int);
Parameters
sig |
Specify the signal to set the signal handler to. It can be an implementation-defined value or one of the following values:
Each library implementation may provide additional signal value macro constants that can be used with this function. | ||||||||||||||
handler |
Specify a pointer to a signal handler function. This must be either a user-defined function or one of the following predefined functions:
If pointer to a function. The signature of the function must follow the following prototype: void handler_function (int sig); |
Return Value
The return type is the same as the type of parameter handler.
If the request is successful, the function returns a pointer to the particular handler function which was in charge of handling this signal before the call, if any. Or either SIG_DFL or SIG_IGN if before the call the signal was being handled by the default handler or was being ignored, respectively.
If the function was not successful in registering the new signal handling procedure, it returns SIG_ERR and errno may be set to a positive value.
Example:
The example below shows the usage of signal() function.
#include <signal.h> #include <stdio.h> volatile sig_atomic_t gSignalStatus = 0; void signal_handler(int signal) { gSignalStatus = signal; } int main(void) { //installing a signal handler signal(SIGINT, signal_handler); printf("SignalValue: %d\n", gSignalStatus); printf("Sending signal %d\n", SIGINT); raise(SIGINT); printf("SignalValue: %d\n", gSignalStatus); return 0; }
The output of the above code will be:
SignalValue: 0 Sending signal 2 SignalValue: 2
❮ C <signal.h> Library