![]() |
![]() |
![]() |
![]() |
Create/access a named semaphore
#include <semaphore.h> sem_t * sem_open( const char * sem_name, int oflags, ... );
libc
The sem_open() function creates or opens a named semaphore. Named semaphores are slower than the unnamed semaphores created with sem_init().
The semaphore descriptor returned by sem_open() can be used with sem_wait(), sem_trywait(), sem_post(), and remains usable until sem_close() is called.
The sem_name argument must start with a / character, such as /myprog.sem1. Semaphores appear under /dev/sem, which would make this example appear in the filesystem as /dev/sem/myprog.sem1. Semaphore names must be less than (NAME_MAX - 8) characters.
![]() |
Semaphore names shouldn't contain / characters except as the first character to maintain POSIX portability. QNX allows extra / characters in semaphore names. |
The oflags argument is only used for semaphore creation.
![]() |
Don't set oflags to O_RDONLY, O_RDWR, or O_WRONLY. A semaphore's behavior is undefined with these flags. The QNX libraries silently ignore these options, but it may reduce your code's portability. |
When creating a new semaphore, oflags can be set to O_CREAT or (O_CREAT|O_EXCL):
For portability, mode should set the read, write, and execute bits to the same value. An easy way of doing this is to use the constants from <sys/stat.h>:
![]() |
Don't mix named semaphore operations (such as sem_open() and sem_close()) with unnamed semaphore operations (such as sem_init() and sem_destroy()) on the same semaphore. |
Semaphores persist as long as the system is up.
A pointer to the created or accessed semaphore, or -1 for failure (errno is set).
Safety: | |
---|---|
Cancellation point | No |
Interrupt handler | No |
Signal handler | Yes |
Thread | Yes |
The mqueue manager must be running for applications to use named semaphores.
sem_close(), sem_unlink(), sem_wait(), sem_trywait(), sem_post(), sem_init(), sem_destroy()
![]() |
![]() |
![]() |
![]() |