C program to set up a real-time clock interval timer using the alarm API

Alarm() function: The alarm API can be called by a process to request the kernel to send the SIGALRM signal after a certain number of real clock seconds. The function prototype ofthe API is:

#include<signal.h>
unsigned int alarm(unsigned int time_interval);
Returns: 0
or number of seconds until previously set alarm pause() function: It waits for signal.
#include<unistd.h>
int pause(void);
The pause() library function causes the invoking process (or thread) to sleep until a signal is received that either terminates it or causes it to call a signal catching function.

The pause() function only returns when a signal was caught and the signal-catching function returned.

In this case pause() returns -1, and errno is set to EINTR.

Sigaction() function: The sigaction API blocks the signal it is catching allowing a process to specify additional signals to be blocked when the API is handling a signal.

The sigaction API prototype is:
#include<signal.h>
int sigaction(int signal_num, struct sigaction* action, struct sigaction* old_action);
Returns: 0 if OK, 1 on error
The struct sigaction data type is defined in the
header as:
struct sigaction
{
void (*sa_handler)(int);
sigset_t sa_mask;
int sa_flag;
}

				
					#include<errno.h>
#include<unistd.h>
#include<stdio.h>
#include<signal.h>
void wakeup()
{
printf(“Hello\n”);
printf(“---------------------------------\n”);
}
int main()
{
int i;
struct sigaction action;
action.sa_handler = wakeup();
action.sa_flags = SA_RESTART;
sigemptyset(&action.sa_mask);
if(sigaction(SIGALRM, &action, 0) == -1)
{
perror(“sigaction”);
}
while(1)
{
alarm(5);
pause();
printf(“Waiting for alarm\n”);
}
return 0;
}

				
			

Output:
Hello
——————————— Waiting For Alarm Hello
——————————— (After 5 CPU Clockcycle)
Waiting For Alarm Hello
——————————— (After 5 CPU Clockcycle)
Waiting For Alarm Hello
———————————
Waiting For Alarm Hello
——————————— (After 5 CPU Clockcycle)
Waiting For Alarm Hello
——————————— (After 5 CPU Clockcycle)
Waiting For Alarm

Leave a Reply