UNIX / OSX semtimedop version

GLibC has a semtimedop method that allows you to perform an operation (in this case, get a semaphore) that expires after a certain time. Win32 also provides WaitForSingleObject , which provides similar functionality.

As far as I can see, there is no equivalent in OSX or other Unices. Can you suggest either an equivalent for semtimedop or a workaround to end the session after a certain period of time.

+4
source share
1 answer

You can exit the semop() call (and most other blocking calls) by receiving a signal, for example, called alarm() .

unverified 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 */ /* ... */ } 
+2
source

All Articles