Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C Library Function - alarm()

C Library Function - alarm()

C Standard Library - <signal.h> C Standard Library -

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

Return Value

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

Notes

C Standard Library - <signal.h> C Standard Library -