C Library Function - strsignal()
Description
strsignal The function is a function in the C standard library, used to get the description string corresponding to a specified signal number. This function is defined in header.
Syntax
char *strsignal(int signum);
Parameters
int signum: The signal number.
Return Value
- On success, returns a pointer to the string describing the signal.
- On failure, returns
NULL.
Example
The following is an example of using strsignal Example program demonstrating the function getting and printing a signal description string. The program sets up a signal handler; when a SIGINT signal is caught, uses the strsignal The function gets the signal description and prints it.
Example
#include
#include
#include
#include
// Signal handler
void
handle_sigint
(
int
sig
)
{
printf
(
"Caught signal %d: %s\n"
,
sig
,
strsignal
(
sig
)
)
;
}
int
main
(
)
{
// Set up the signal handler for SIGINT
signal
(
SIGINT
,
handle_sigint
)
;
// Infinite loop, waiting for the 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 send SIGINT signal, and 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 catches a SIGINT signal, it calls the handle_sigint signal handler, and uses strsignal The function gets the description string corresponding to the signal number, then prints the signal number and the description string.
Explanation
signal(SIGINT, handle_sigint);: set theSIGINTThe signal handler forhandle_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 a specified signal number.- The returned description string is managed by the library function and should not be modified or freed.
C Standard Library -