tags:

views:

39

answers:

2

I have the following code which I'd hope would wait 2 seconds then wait 5 seconds in a loop.

There is a reason why I'm not using the it_interval to refire the timer.

#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <signal.h>
#include <time.h>
#include <sys/time.h>

#include <semaphore.h>

sem_t sem;

void sighdlr( int sig )
{
    printf( "sighdlr\n" );
    sem_post( &sem );
}

int main( int c, char *v[] )
{
    signal( SIGALRM, sighdlr );

    struct itimerval itv;
    struct tm tm;
    time_t now;

    while( true )
    {
        itv.it_value.tv_sec = 2;
        itv.it_value.tv_usec = 0;
        itv.it_interval.tv_sec = 0;
        itv.it_interval.tv_usec = 0;
        setitimer( ITIMER_REAL, &itv, NULL );

        sem_wait( &sem );
        now = time( NULL );
        localtime_r( &now, &tm );
        fprintf( stderr, "%02d:%02d:%02d\n", tm.tm_hour, tm.tm_min, tm.tm_sec );

        itv.it_value.tv_sec = 5;
        itv.it_value.tv_usec = 0;
        itv.it_interval.tv_sec = 0;
        itv.it_interval.tv_usec = 0;
        setitimer( ITIMER_REAL, &itv, NULL );

        sem_wait( &sem );
        now = time( NULL );
        localtime_r( &now, &tm );
        fprintf( stderr, "%02d:%02d:%02d\n", tm.tm_hour, tm.tm_min, tm.tm_sec );
    }
}

It produces the following output

sighdlr
15:32:50
15:32:50
sighdlr
15:32:52
15:32:52
sighdlr
15:32:54
15:32:54
sighdlr
15:32:56
15:32:56
sighdlr
15:32:58
15:32:58
sighdlr
15:33:00
15:33:00

I can't work out why it isn't waiting for the 5 seconds for the second timer.

Any ideas?

Thx M.

+1  A: 

Aha!. fixed it.

the sem_wait was being interrupted and returning -1 and errno == EINTR so I have to have something like this.

do {
    ret = sem_wait( &sem );
} while( ret < 0 && errno == EINTR );
ScaryAardvark
A: 

i am missing an explicit call to sem_init().

Peter Miehle
I agree that I should include a call to sem_init but as sem is static it'll be zeroed anyway.
ScaryAardvark