#include <pthread.h>
#include <sys/time.h>
#include <unistd.h>
#include <signal.h>
#include <stdlib.h>

void handler(int signum)
{
    /* do nothing */
}


double diff(struct timeval *before, struct timeval *after)
{
    double x, y;
    x = before->tv_sec + before->tv_sec * 1e-6;
    y = after->tv_sec + after->tv_sec * 1e-6;
    return y - x;
}

int main()
{
    struct timeval before, after;
    struct timespec timeout;
    pthread_mutex_t mutex;
    pthread_cond_t cond;
    int rc;
    double dt;

    (void)pthread_mutex_init(&mutex, NULL);
    (void)pthread_cond_init(&cond, NULL);

    (void) pthread_mutex_lock(&mutex);
    clock_gettime(CLOCK_REALTIME, &timeout);
    timeout.tv_sec += 2;

    signal(SIGALRM, handler);
    signal(SIGINT, handler);

    gettimeofday(&before, NULL);
    alarm(1);
    rc = pthread_cond_timedwait(&cond, &mutex, &timeout);
    gettimeofday(&after, NULL);

    (void) pthread_mutex_unlock(&mutex);

    (void)pthread_cond_destroy(&cond);
    (void)pthread_mutex_destroy(&mutex);

    dt = diff(&before, &after);

    if (1.5 <= dt)
        /* pthread_cond_timedwait() restarted after SIGALRM */
        exit(1);
    else
        /* pthread_cond_timedwait() interrupted after 1 second */
        exit(0);
}

