C Library Function - pause()
pause is a function in the C standard library used to suspend a process (pause execution) until a signal is caught. This function is defined in header.
Syntax
int pause(void);
Parameters
pause The function takes no arguments.
Return Value
- On success
pausethe function does not return, because the process is interrupted by the signal handler. - On failure, it returns -1 and sets
errnotoEINTR, indicating that the function was interrupted by a signal.
Example
The following is an example of using pause An example program for the function. This program sets up a signal handler that, upon catching a SIGINT signal (typically triggered by Ctrl+C), releases the suspension.
Example
#include
#include
#include
// Signal handler
void
handle_sigint
(
int
sig
)
{
printf
(
"Caught signal %d\n"
,
sig
)
;
}
int
main
(
)
{
// Set up the signal handler for SIGINT
signal
(
SIGINT
,
handle_sigint
)
;
// Suspend the process, waiting 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 (sending a SIGINT signal), the output will be:
Explanation
signal(SIGINT, handle_sigint);: set theSIGINTThe signal handler forhandle_sigint.pause();: Suspend the process, waiting for a signal to arrive. When aSIGINTsignal is caught,handle_sigintthe function is called.- After the signal handler executes,
pausethe function returns -1 and the program continues executing the subsequent code.
Notes
pauseThe function is typically used in signal-driven programs to suspend a process while waiting for a specific signal.- in
pauseWhile the function is suspending, the process's execution is paused until a signal is caught. - When handling signals, pay attention to signal safety; a signal handler should be as short as possible and only perform safe operations.
C Standard Library -