I'm using sem_open
and sem_close
to create and destroy semaphores because sem_init
and sem_destroy
are deprecated on OS X.
The first time I run my program, the semaphore functions as expected. At the end of my program, I call sem_close
and it returns without an error.
However, if I run the program again, sem_open
fails with errno EEXIST:
Both O_CREAT and O_EXCL were specified in oflag, but a semaphore with this name already exists.
Not only did the sem_close
function return successfully during the first run, but the man file suggests that the semaphores are closed on process termination regardless:
All open named semaphores are automatically closed on process termination
So I am mystified as to why the semaphore persists.
MCVE
// file: pc.cc
#include <semaphore.h>
#include <pthread.h>
#include <cstdio>
#include <cstdlib>
#include <errno.h>
int main(int argc, char *argv[])
{
errno = 0;
sem_t *semaphore = sem_open("/sem3", O_CREAT | O_EXCL, 0, 0);
if (semaphore == SEM_FAILED) {
int err1 = errno;
fprintf(stderr, "sem_open() failed. errno:%d\n", err1);
if (EEXIST == err1)
fprintf(stderr, "EEXIST : Both O_CREAT and O_EXCL were specified in oflag, but a semaphore with this name already exists. \n");
}
errno = 0;
if(sem_close(semaphore) == -1){
int err2 = errno;
fprintf(stderr, "sem_close() failed. errno:%d\n", err2);
if( EINVAL == err2)
fprintf(stderr, "EINVAL : sem is not a valid semaphore.");
}
return 0;
}
Output from first and second run
$ ./output_test
$ ./output_test
sem_open() failed. errno:17
EEXIST : Both O_CREAT and O_EXCL were specified in oflag, but a semaphore with this name already exists.
sem_close() failed. errno:9