C Standard Library -<signal.h>
Introduction
<signal.h>It is a header file in the C standard library used for handling signals.
signal.hThe header file defines a variable typesig_atomic_ttwo function calls, and some macros to handle different signals reported during program execution.
A signal is an asynchronous notification mechanism that allows a process to execute a predefined handler function when a specific event occurs.
Below is a simple example program demonstrating how to use the signal function to catch the SIGINT signal (usually generated by Ctrl+C).
Example
#include <signal.h>
#include <unistd.h>
// Global variable indicating whether the program should exit
volatile sig_atomic_t stop = 0;
void handle_sigint(int sig) {
printf("Caught signal %d\n", sig);
stop = 1; // Set the exit flag
}
int main() {
// Set the handler for the SIGINT signal to the handle_sigint function
signal(SIGINT, handle_sigint);
while (!stop) { // Check whether to exit
printf("Running...\n");
sleep(1);
}
printf("Exiting...\n");
return 0;
}
In the above code, when the program is running, if the user pressesCtrl+C, it will catch the SIGINT signal and call the handle_sigint function, printing the signal number.
Compile and execute the above code, the output is as follows:
Running... Running... Running... ^CCaught signal 2 Exiting...
Code Analysis:
volatile sig_atomic_t stop = 0;: define a global variablestop, used to indicate whether the program should exit. Usingvolatilethe keyword ensures that the compiler will not optimize away accesses to this variable, because it may be modified in a signal handler.sig_atomic_tThe type guarantees that accesses to this variable are atomic.- In
handle_sigintIn the signal handler function, setstopto 1, indicating the program should exit. - In the main loop, check
stopthe value of the variable; if it is set to 1, break out of the loop and end the program.
Library variables
The following are variable types defined in the header file signal.h:
| Serial Number | Variables & Description |
|---|---|
| 1 | sig_atomic_t This isintType, used as a variable in signal handlers. It is an integer type of an object that can be accessed as an atomic entity even in the presence of asynchronous signals. |
| 2 | sigset_t A data type used to represent a signal set. |
Library macros
<In the C standard library,SIG_Prefix macros andsignalUsed together with functions to define and handle signal behavior. The following are commonSIG_Macros and their uses:
| Serial Number | Macros & Description |
|---|---|
| 1 | SIG_DFL Represents the default handler for a signal. Use this macro to restore a signal to its default behavior. |
| 2 | SIG_ERR Represents the return value when an error occurs in setting a signal handler function. |
| 3 | SIG_IGN Ignore signal. |
Signal types:
| Constants | Description |
|---|---|
SIGABRT | byabortThe signal generated by the function, indicating abnormal termination |
SIGALRM | byalarmThe timer expiration signal set by the function |
SIGBUS | Illegal memory access (for example, accessing an unaligned memory address) |
SIGCHLD | Child process status changed (exited or stopped) |
SIGCONT | Continue executing a suspended process |
SIGFPE | Arithmetic errors (for example, division by zero, floating-point exceptions) |
SIGHUP | Hangup signal (usually used to detect terminal disconnect) |
SIGILL | Illegal instruction |
SIGINT | Interrupt signal (usually generated by Ctrl+C) |
SIGKILL | Immediate termination signal (cannot be caught or ignored) |
SIGPIPE | Write data to a pipe with no read process |
SIGQUIT | Terminal quit signal (usually generated by Ctrl+\), produces a core dump |
SIGSEGV | Segmentation fault (illegal memory access) |
SIGSTOP | Stops process execution (cannot be caught or ignored) |
SIGTERM | Termination signal |
SIGTSTP | Suspends the process (usually generated by Ctrl+Z) |
SIGTTIN | Signal generated when a background process reads data from the terminal |
SIGTTOU | Signal generated when a background process writes data to the terminal |
SIGUSR1 | User-defined signal 1 |
SIGUSR2 | User-defined signal 2 |
SIGPOLL | I/O event (replaces SIGIO) |
SIGPROF | Timer expiration signal (bysetitimerthe set profiling timer) |
SIGSYS | Illegal system call |
SIGTRAP | Breakpoint or trap instruction |
SIGURG | Socket urgent condition signal |
SIGVTALRM | Virtual clock timer expiration signal |
SIGXCPU | Exceeded CPU time limit |
SIGXFSZ | Exceeded file size limit |
Library functions
The following are functions defined in the header file signal.h:
| Function | Description |
|---|---|
void (*signal(int sig, void (*func)(int)))(int); |
Set the signal handler. |
int raise(int sig); |
Send a signal to the current process. |
int kill(pid_t pid, int sig); |
Send a signal to the specified process. |
int sigprocmask(int how, const sigset_t *set, sigset_t *oldset); |
Check or change the blocked signal set. |
int sigaction(int sig, const struct sigaction *act, struct sigaction *oldact); |
Check or change the signal handler. |
int sigsuspend(const sigset_t *mask); |
Temporarily replace the current signal mask and suspend the process until a signal is caught. |
int sigpending(sigset_t *set); |
Check the pending signal set. |
int sigemptyset(sigset_t *set); |
Initialize the signal set to an empty set. |
int sigfillset(sigset_t *set); |
Initialize the signal set to the full signal set. |
int sigaddset(sigset_t *set, int signum); |
Add the specified signal to the signal set. |
int sigdelset(sigset_t *set, int signum); |
Remove the specified signal from the signal set. |
int sigismember(const sigset_t *set, int signum); |
Check whether the specified signal is in the signal set. |
void abort(void); |
raiseSIGABRTThe signal causes abnormal termination of the process. |
unsigned int alarm(unsigned int seconds); |
After the specified number of seconds, sendSIGALRMsignal to the calling process. |
int pause(void); |
Suspend the process until a signal is caught. |
void psignal(int sig, const char *s); |
Print signal description information. |
char *strsignal(int sig); |
Return the signal description string. |
int sigwait(const sigset_t *set, int *sig); |
Block waiting for a signal and handle it. |