You are not logged in.
Pages: 1
timer is invoked every 1 sec but while loop is being
iterated every 30 sec. So while loop should print value of i
value of i 0
value of i 30
value of i 60
but on running in Linux following output is coming.
/root$ a.out
Value of 1
Value of 2
Value of 3
Value of 4
Value of 5
Can any body tell me why it is happening like this ?
#include<time.h>
#include<signal.h>
#include<stdlib.h>
#include<memory.h>
#include<stdio.h>
static int i = 0;
void my_fun()
{
++i;
}
int sync_timer()
{
clock_t clock = CLOCK_REALTIME;
//int signum = SIGUSR1;
int signum = SIGTERM;
int status;
timer_t timer_id;
struct itimerspec ts;
struct sigevent se;
struct sigaction act;
sigfillset(&act.sa_mask);
act.sa_flags = 0;
act.sa_handler = my_fun;
sigaction(signum, &act, NULL);
/* Set up timer: */
memset(&se, 0, sizeof(se));
se.sigev_notify = SIGEV_SIGNAL;
se.sigev_signo = signum;
se.sigev_value.sival_int = 0;
status = timer_create(clock, &se, &timer_id);
if (status < 0) {
perror("timer_create");
return -1;
}
ts.it_interval.tv_sec = 1;
ts.it_interval.tv_nsec = 0;
ts.it_value = ts.it_interval;
status = timer_settime(timer_id, 0, &ts, NULL);
if (status < 0) {
perror("timer_settime");
return -1;
}
return 1;
}
main()
{
sync_timer();
while(1){
sleep(30);
printf("Value of %d\n", i);
}
}
thanks..........
Offline
It's because the sleep() gets interrupted by the timer signal,
so you get the printf every second instead of every 30 seconds.
You have to check the return value of sleep() and call sleep again
for the remaining time. See the manpage of sleep: man 3 sleep.
Offline
Pages: 1