views:

19

answers:

1

Can you help me to understand why it is recommended to use:

while ((s = sem_timedwait(&sem, &ts)) == -1 && errno == EINTR)
    continue; // Restart when interrupted by handler

(EINTR: The call was interrupted by a signal handler)

Instead of simply:

s = sem_timedwait(&sem, &ts);

In witch cases I have to manage EINTR ?

+1  A: 

The loop will cause the system call to be restarted if a signal is caught during the execution of the system call, so it will not go on to the next statement unless the system call has either succeeded or failed (with some other error). Otherwise the thread will continue execution with the next statement when the system call is interrupted by a signal handler.

For example, if you want to be able to abort this sem_timedwait() by sending a particular signal to the thread, then you would not want to unconditionally restart the system call. Instead you may want to mark that the operation was aborted and clean up. If you have multiple signal handlers, the signal handler can set a flag which can be checked when EINTR is encountered in order to determine whether to restart the system call.

This only matters if the thread catches any signals using a signal handler, and the sigaction() SA_RESTART flag was not used to automatically restart any interrupted system call. However, if you are not using any signal handlers and did not intend for your code to be affected by a signal handler, it is still good practice to use the loop so that it will continue to work as you intended even if your code is later used in the same program as other code which uses signal handlers for unrelated purposes.

mark4o
Thanks for the answer, now it's clear.
Soubok