sem_trywait and sem_wait Subroutine

Purpose

Locks a semaphore.

Library

Standard C Library (libc.a)

Syntax

#include <semaphore.h>

int sem_trywait (sem)
sem_t *sem;

int sem_wait (sem)
sem_t *sem;

Description

The sem_trywait subroutine locks the semaphore referenced by the sem parameter only if the semaphore is currently not locked; that is, if the semaphore value is currently positive. Otherwise, it does not lock the semaphore.

The sem_wait subroutine locks the semaphore referenced by the sem parameter by performing a semaphore lock operation on that semaphore. If the semaphore value is currently zero, the calling thread does not return from the call to the sem_wait subroutine until it either locks the semaphore or the call is interrupted by a signal.

Upon successful return, the state of the semaphore will be locked and will remain locked until the sem_post subroutine is executed and returns successfully.

The sem_wait subroutine is interruptible by the delivery of a signal.

Parameters

Item Description
sem Specifies the semaphore to be locked.

Return Values

The sem_trywait and sem_wait subroutines return zero if the calling process successfully performed the semaphore lock operation. If the call was unsuccessful, the state of the semaphore is unchanged, and the subroutine returns -1 and sets errno to indicate the error.

Error Codes

The sem_trywait and sem_wait subroutines fail if:
Item Description
EACCES Permission is denied to access the unnamed semaphore.
EAGAIN The semaphore was already locked, so it cannot be immediately locked by the sem_trywait subroutine.
EFAULT Invalid user address.
EIDRM Semaphore was removed during the required operation.
EINTR A signal interrupted the subroutine.
EINVAL The sem parameter does not refer to a valid semaphore.
ENOMEM Insufficient memory for the required operation.
ENOTSUP This function is not supported with processes that have been checkpoint-restart'ed.