views:

260

answers:

1

GLibC has a method semtimedop which allows you to perform an operation (a semaphore acquire in this case) which times out after a certain amount of time. Win32 also provides WaitForSingleObject which provides similar functionalty.

As far as I can see there is no equivalent on OSX or other Unices. Can you suggest either the equivalent for semtimedop or a workaround to terminate a semop after a certain amount of time cleanly.

+2  A: 

You can break out of a semop() call (and most other blocking calls) by getting a signal, such as one caused by alarm().

untested example:

#include <signal.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>

volatile int alarm_triggered = 0;
void alarm_handler(int sig)
{
    alarm_triggered = 1;
}

int main(int argc, char **argv)
{
    int rc;
    /* set up signal handler */
    signal(SIGALRM, alarm_handler);

    /* ... */
    alarm(30); /* 30 second timeout */
    rc = semop(...);
    if (rc == -1 && errno == EINTR)
    {
        if (alarm_triggered)
        {
            /* timed out! */
        }
    }
    alarm(0); /* disable alarm */
    /* ... */
}
Hasturkun
Is the alarm call available on Windows too?
Mike McQuaid
No, `alarm()` is a POSIX call, and I don't think Windows supports the concept of signals.(btw, I edited my answer, was actually written as two separate parts)
Hasturkun
Thanks. Also, the pthreads stuff is of no use as it's not a kernel-level semaphore so won't work across processes.
Mike McQuaid
True, I'll remove the second part of my answer
Hasturkun