sem_init Subroutine

Purpose

Initializes an unnamed semaphore.

Library

Standard C Library (libc.a)

Syntax

#include <semaphore.h>

int sem_init (sem, pshared, value)
sem_t *sem;
int pshared;
unsigned value;

Description

The sem_init subroutine initializes the unnamed semaphore referred to by the sem parameter. The value of the initialized semaphore is contained in the value parameter. Following a successful call to the sem_init subroutine, the semaphore might be used in subsequent calls to the sem_wait, sem_trywait, sem_post, and sem_destroy subroutines. This semaphore remains usable until it is destroyed.

If the pshared parameter has a nonzero value, the semaphore is shared between processes. In this case, any process that can access the sem parameter can use it for performing sem_wait, sem_trywait, sem_post, and sem_destroy operations.

Only the sem parameter itself may be used for performing synchronization.

If the pshared parameter is zero, the semaphore is shared between threads of the process. Any thread in this process can use the sem parameter for performing sem_wait, sem_trywait, sem_post, and sem_destroy operations. The use of the semaphore by threads other than those created in the same process returns an error.

Attempting to initialize a semaphore that has been already initialized results in the loss of access to the previous semaphore.

Parameters

Item Description
sem Specifies the semaphore to be initialized.
pshared Determines whether the semaphore can be shared between processes or not.
value Contains the value of the initialized semaphore.

Return Values

Upon successful completion, the sem_init subroutine initializes the semaphore in the sem parameter. Otherwise, it returns -1 and sets errno to indicate the error.

Error Codes

The sem_init subroutine fails if:
Item Description
EFAULT Invalid user address.
EINVAL The value parameter exceeds SEM_VALUE_MAX.
ENFILE Too many semaphores are currently open in the system.
ENOMEM Insufficient memory for the required operation.
ENOSPC A resource required to initialize the semaphore has been exhausted, or the limit on semaphores, SEM_NSEMS_MAX, has been reached.
ENOTSUP This function is not supported with processes that have been checkpoint-restart'ed.