sem_timedwait Subroutine

Purpose

Locks a semaphore (ADVANCED REALTIME).

Syntax

#include <semaphore.h>
#include <time.h>

int sem_timedwait(sem_t *restrict sem,
       const struct timespec *restrict abs_timeout);  

Description

The sem_timedwait() function locks the semaphore referenced by sem as in the sem_wait() function. However, if the semaphore cannot be locked without waiting for another process or thread to unlock the semaphore by performing a sem_post() function, this wait terminates when the specified timeout expires.

The timeout expires when the absolute time specified by abs_timeout passes—as measured by the clock on which timeouts are based (that is, when the value of that clock equals or exceeds abs_timeout)—or when the absolute time specified by abs_timeout has already been passed at the time of the call.

If the Timers option is supported, the timeout is based on the CLOCK_REALTIME clock. If the Timers option is not supported, the timeout is based on the system clock as returned by the time() function. The resolution of the timeout matches the resolution of the clock on which it is based. The timespec data type is defined as a structure in the <time.h> header.

The function never fails with a timeout if the semaphore can be locked immediately. The validity of the abs_timeout parameter does not need to be checked if the semaphore can be locked immediately.

Application Usage

The sem_timedwait() function is part of the Semaphores and Timeouts options and need not be provided on all implementations.

Return Values

The sem_timedwait() function returns 0 if the calling process successfully performed the semaphore lock operation on the semaphore designated by sem. If the call was unsuccessful, the state of the semaphore remains unchanged, the function returns a value of -1, and errno is set to indicate the error.

Error Codes

The sem_timedwait() function fails if:

Item Description
[EFAULT] abs_timeout references invalid memory.
[EINVAL] The sem argument does not refer to a valid semaphore.
[EINVAL] The process or thread would have blocked, and the abs_timeout parameter specified a nanoseconds field value less than 0 or greater than or equal to 1000 million.
[ETIMEDOUT] The semaphore could not be locked before the specified timeout expired.

The sem_timedwait() function might fail if:

Item Description
[EDEADLK] A deadlock condition was detected.
[EINTR] A signal interrupted this function.