sem_open

Synopsis

#include <semaphore.h>

sem_t *sem_open(const char *name, int oflag, ... /* mode_t mode, unsigned int value */);

Status

Partially implemented

Conformance

IEEE Std 1003.1-2024

Description

The sem_open() function shall establish a connection between a named semaphore and the calling process, returning a semaphore that may be used in subsequent calls to sem_wait(), sem_timedwait(), sem_trywait(), sem_post(), sem_getvalue() and sem_close().

name shall consist of a single path component, optionally preceded by one /; the two forms refer to the same semaphore. Its length shall not exceed NAME_MAX.

If O_CREAT is set in oflag, two further arguments are expected: a mode_t mode and an unsigned int value, which shall not exceed SEM_VALUE_MAX. If O_CREAT and O_EXCL are both set, sem_open() shall fail when the semaphore already exists. If O_CREAT is set without O_EXCL, an existing semaphore is opened and mode and value are ignored.

Named semaphores live in posixsrv, which publishes each of them as a device node under /dev/posix/sem/. The returned semaphore holds a file descriptor on that node, opened with O_CLOEXEC, so it is closed across a successful exec() and released by the server when the process exits.

Each successful call returns a distinct sem_t, holding its own descriptor, even when the same name is opened more than once in one process. They all refer to the same semaphore in the server, and each must be released with its own sem_close(). IEEE Std 1003.1-2024 leaves this implementation-defined; IEEE Std 1003.1-2017 required the same address to be returned for every such call, so this is conformant only from the 2024 edition on.

The number of semaphores that may exist at one time is bounded by SEM_NSEMS_MAX, the value reported by sysconf(_SC_SEM_NSEMS_MAX).

Return value

Upon successful completion, sem_open() shall return the address of the semaphore. Otherwise it shall return SEM_FAILED and set errno to indicate the error.

Errors

This function shall fail if:

  • EACCES - the named semaphore exists but the permissions specified by oflag are denied,

  • EEXIST - O_CREAT and O_EXCL are both set and the named semaphore already exists,

  • EINVAL - name is not a valid semaphore name, or value exceeds SEM_VALUE_MAX,

  • ENAMETOOLONG - the length of name exceeds NAME_MAX,

  • ENOENT - O_CREAT is not set and the named semaphore does not exist,

  • ENOMEM - insufficient memory is available,

  • ENOSPC - there is insufficient space for the new semaphore, or SEM_NSEMS_MAX semaphores already exist.

POSIX deviations

The mode argument of sem_open() is accepted but ignored. Named semaphores are published as device nodes by posixsrv through create_dev(), which takes no mode argument, so every semaphore is created with the same fixed permissions regardless of the requested mode and the file mode creation mask.