UNIX Socket FAQ

A forum for questions and answers about network programming on Linux and all other Unix-like systems

You are not logged in.

#1 2012-03-03 08:59 PM

useless79
Member
Registered: 2011-10-10
Posts: 30

unix timer

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

#2 2012-03-04 06:02 AM

i3839
Oddministrator
From: Amsterdam
Registered: 2003-06-07
Posts: 2,231

Re: unix timer

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

#3 2012-03-04 04:01 PM

RobSeace
Administrator
From: Boston, MA
Registered: 2002-06-12
Posts: 3,829
Website

Re: unix timer

Or, in this case, since you know your sleep() is going to get interrupted every second, it's kind of pointless to even use sleep() at all...  Just use pause(), and then check the value of "i" to see how long you've been asleep...  Ie:

for (;;) {
    pause();
    if ((i % 30) == 0)
        printf ("Value of %d\n", i);
}

Also, please remember to use the code tags around large blocks of code for better readability...

Offline

#4 2012-03-04 07:19 PM

useless79
Member
Registered: 2011-10-10
Posts: 30

Re: unix timer

Thanks Rob and i3839.

Offline

Board footer

Powered by FluxBB