C Library Function - alarm()
Description
alarm The function is part of the C standard library and is used to send a SIGALRM signal to the calling process after a specified time. This function is defined in header.
Syntax
unsigned int alarm(unsigned int seconds);
Parameters
unsigned int seconds: Specifies after how many seconds to send theSIGALRMsignal. If the argument is 0, any previously set alarm is canceled.
Return Value
- On success, it returns the remaining time (in seconds) of a previously set alarm.
- If no alarm was previously set, it returns 0.
Example
The following is an example of using alarm An example program where the function sets an alarm and handles the SIGALRM signal. The program sends a SIGALRM signal after 5 seconds and runs the corresponding signal handler when the signal is caught.
Example
#include
#include
#include
// Signal handler
void
handle_sigalrm
(
int
sig
)
{
printf
(
"Caught signal %d: Alarm triggered\n"
,
sig
)
;
}
int
main
(
)
{
// Set up the signal handler for SIGALRM
signal
(
SIGALRM
,
handle_sigalrm
)
;
// Set an alarm to trigger SIGALRM after 5 seconds
alarm
(
5
)
;
printf
(
"Alarm set for 5 seconds\n"
)
;
// Infinite loop, waiting for the signal
while
(
1
)
{
printf
(
"Running...\n"
)
;
sleep
(
1
)
;
}
return
0
;
}
Running the above example program may produce the following output:
Alarm set for 5 seconds
Running...
Running...
Running...
Running...
Running...
Caught signal 14: Alarm triggered
The program sets a 5-second alarm and, when it catches the SIGALRM signal, executes the handle_sigalrm signal handler, which outputs the corresponding message.
Explanation
signal(SIGALRM, handle_sigalrm);: set theSIGALRMThe signal handler forhandle_sigalrm.alarm(5);is as follows: set an alarm to send aSIGALRMsignal after 5 seconds.- The program enters an infinite loop, printing once per second
Running..., until it catches aSIGALRMsignal, execute the signal handler and printCaught signal 14: Alarm triggered.
Notes
alarmThe alarm set by the function will send aSIGALRMsignal to the calling process.- You can cancel a previously set alarm by calling the
alarmfunction again and passing an argument of 0. - A signal handler should be as short and efficient as possible, performing only safe operations.
C Standard Library -