C library functions -pause()
C Standard Library - <signal.h>
pauseThe function is a function in the C standard library, used to suspend (pause execution) a process until a signal is caught. This function is defined in<unistd.h>In the header file.
Syntax
int pause(void);
Parameter
pauseThe function accepts no parameters.
Return Value
- On success
pauseThe function does not return, because the process is interrupted by the signal handler. - On failure, it returns -1, and will
errnoSet toEINTR, indicating that the function was interrupted by a signal.
Example
The following is an example usingpauseExample program of the function. This program sets up a signal handler that, when catchingSIGINTsignal (usually triggered by Ctrl+C), resumes from suspension.
Example
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
// Signal handler
void handle_sigint(int sig) {
printf("Caught signal %d\n", sig);
}
int main() {
// Set the signal handler for SIGINT
signal(SIGINT, handle_sigint);
// Suspend the process, wait for a signal
printf("Waiting for SIGINT (press Ctrl+C)...\n");
pause();
printf("Exiting...\n");
return 0;
}
#include <signal.h>
#include <unistd.h>
// Signal handler
void handle_sigint(int sig) {
printf("Caught signal %d\n", sig);
}
int main() {
// Set the signal handler for SIGINT
signal(SIGINT, handle_sigint);
// Suspend the process, wait for a signal
printf("Waiting for SIGINT (press Ctrl+C)...\n");
pause();
printf("Exiting...\n");
return 0;
}
After compiling and running the program, the output will be:
Waiting for SIGINT (press Ctrl+C)...
When Ctrl+C is pressed (sendingSIGINTsignal), the output will be:
Explanation
signal(SIGINT, handle_sigint);: SettingsSIGINTThe signal handler ishandle_sigint。pause();: suspends the process, waiting for a signal to arrive. When catchingSIGINTWhen a signal occurs,handle_sigintThe function is called.- After the signal handler executes,
pausethe function returns -1, and the program continues executing subsequent code.
Notes
pauseThe function is typically used in signal-driven programs to suspend a process and wait for a specific signal.- In
pauseWhile the function is suspending, process execution is paused until a signal is caught. - When handling signals, signal safety should be noted; the signal handler should be as short as possible and only perform safe operations.