C library function -strsignal()
C Standard Library - <signal.h>
Description
strsignalThe function is a function in the C standard library, used to obtain the description string corresponding to the specified signal number. This function is defined in<string.h>In the header file.
Syntax
char *strsignal(int signum);
Parameter
int signum: Signal number.
Return Value
- On success, returns a pointer to the string describing the signal.
- Return on failure
NULL。
Example
The following is an example of usingstrsignalAn example program in which the function obtains and prints the signal description string. The program sets a signal handler, and when it catchesSIGINTsignal, usestrsignalThe function gets the signal description and prints it.
Example
#include <signal.h>
#include <string.h>
#include <unistd.h>
// Signal handler
void handle_sigint(int sig) {
printf("Caught signal %d: %s\n", sig, strsignal(sig));
}
int main() {
// Set the signal handler for SIGINT
signal(SIGINT, handle_sigint);
// Infinite loop, waiting for signal
while (1) {
printf("Running... Press Ctrl+C to send SIGINT\n");
sleep(1);
}
return 0;
}
After compiling and running the program, press Ctrl+C to sendSIGINTthe signal, the output will be:
Running... Press Ctrl+C to send SIGINT Running... Press Ctrl+C to send SIGINT Running... Press Ctrl+C to send SIGINT Caught signal 2: Interrupt
When the program catchesSIGINTsignal, it callshandle_sigintthe signal handler, and usestrsignalThe function obtains the description string corresponding to the signal number, then prints the signal number and the description string.
Explanation
signal(SIGINT, handle_sigint);: SettingsSIGINTthe signal handler ishandle_sigint。strsignal(sig): In the signal handler, usestrsignalthe function to get the signal numbersigthe corresponding description string.printf("Caught signal %d: %s\n", sig, strsignal(sig));: Print the signal number and description string.
Notes
strsignalThe function is used to obtain the description string corresponding to the specified signal number.- The returned description string is managed by the library function and should not be modified or freed.