C library function -alarm()

C Standard Library - <signal.h>

Description

alarmThe function is a function in the C standard library, used to send after a specified time.SIGALRMSignal to the calling process. This function is defined in<unistd.h>In the header file.

Syntax

unsigned int alarm(unsigned int seconds);

Parameter

  • unsigned int seconds: specifies after how many seconds to sendSIGALRMSignal. If the parameter is 0, any previously set alarm is canceled.

Return Value

  • On success, returns the time remaining on the previously set alarm (in seconds).
  • If there is no previously set alarm, returns 0.

Example

The following is an example usingalarmThe function sets an alarm and handlesSIGALRMExample program for the signal. The program sends after 5 secondsSIGALRMsignal, and executes the corresponding signal handler when the signal is caught.

Example

#include <stdio.h>
#include <signal.h>
#include <unistd.h>

// Signal handler
void handle_sigalrm(int sig) {
    printf("Caught signal %d: Alarm triggered\n", sig);
}

int main() {
    // Set the signal handler for SIGALRM
    signal(SIGALRM, handle_sigalrm);

    // Set an alarm to trigger the SIGALRM signal after 5 seconds
    alarm(5);
    printf("Alarm set for 5 seconds\n");

    // Infinite loop, waiting for signal
    while (1) {
        printf("Running...\n");
        sleep(1);
    }

    return 0;
}

Running the above example program, the possible output is as follows:

Alarm set for 5 seconds
Running...
Running...
Running...
Running...
Running...
Caught signal 14: Alarm triggered

The program sets a 5-second alarm, and upon catching,SIGALRMExecute on signalhandle_sigalrmthe signal handler outputs the corresponding message.

Explanation

  • signal(SIGALRM, handle_sigalrm);: SettingsSIGALRMthe signal handler ishandle_sigalrm。
  • alarm(5);: sets an alarm, sends after 5 secondsSIGALRMsignal.
  • The program enters an infinite loop, printing once every second.Running..., until capturingSIGALRMsignal, executes the signal handler and printsCaught signal 14: Alarm triggered。

Notes

  • alarmThe alarm set by the function will send after the specified time.SIGALRMsignal to the calling process.
  • can be done by calling againalarmThe function also passes parameter 0 to cancel a previously set alarm.
  • Signal handlers should be as short and efficient as possible, and only perform safe operations.

C Standard Library - <signal.h>

other extensions