C program on how to use alarm() and on how SIGALRM signal works
From Linux Man Page
1. alarm() arranges for a SIGALRM signal to be delivered to the calling process in seconds seconds.
2. If seconds is zero, any pending alarm is canceled.
3. In any event any previously set alarm() is canceled.
#include <stdio.h>
#include <stdbool.h>
#include <unistd.h>
#include <sys/time.h>
#include <time.h>
#include <math.h>
#include <string.h>
volatile sig_atomic_t flag = false;
/***************************************************************
* SIGNAL HANDLER for SIGALRM
***************************************************************/
void handle_alarm(int sig) {
flag = true;
}
void print_current_time(void) {
char buffer[26];
int millisec;
struct tm* tm_info;
struct timeval tv;
memset(buffer, '\0', sizeof(buffer));
gettimeofday(&tv, NULL);
/*
* Round to nearest millisec.
*/
millisec = lrint(tv.tv_usec/1000.0);
/*
* Allow for rounding up to nearest second.
*/
if (millisec >= 1000) {
millisec -=1000;
tv.tv_sec++;
}
tm_info = localtime(&tv.tv_sec);
strftime(buffer, 26, "%Y:%m:%d %H:%M:%S", tm_info);
printf("current Time: %s.%03d\n", buffer, millisec);
return;
}
int main()
{
/*
* Register SIGALRM
*/
signal( SIGALRM, handle_alarm );
/*
* Initially, let the timer expire in 1 sec so that the SIGALRM signal
* handler will be invoked and the flag will be set to 'True'
*/
alarm( 1 );
for (;;) {
if (flag) {
flag = false;
/*
* The flag would be set to 'true', only when the process receives
* SIGALRM
*/
alarm(2);
/*
* You would see this print every 2 secs.
*/
print_current_time();
}
}
}
Output:
./a.out
current Time: 2018:08:09 01:36:20.383
current Time: 2018:08:09 01:36:22.383
current Time: 2018:08:09 01:36:24.384
current Time: 2018:08:09 01:36:26.384
current Time: 2018:08:09 01:36:28.384
current Time: 2018:08:09 01:36:30.384
current Time: 2018:08:09 01:36:32.384
current Time: 2018:08:09 01:36:34.384