While trying to open a semaphore sem_open fails. errno is 22 (), which perror describes as "Invalid argument". I've checked the format of the name (which I think is correct), as well as the flags (O_CREAT and O_EXCL seem pretty hard to mess up. What am I not seeing?
Platform is OS X 10.7. I would have preferred to use a nameless semaphore, but the OS doesn't support sem_init.
int name_counter = 0;
// In order to create a unique semaphore, we iterate until we find a name that
// does not already exist.
do {
char name[48] = {0};
sprintf(name, "xyz_sem_%d", name_counter++);
job_semaphore = sem_open(name, O_CREAT | O_EXCL, S_IWUSR | S_IRUSR | S_IRGRP | S_IROTH, 0);
} while(errno == EEXIST);
if(0 != errno)
perror("Error opening xyz semaphore");
assert(0 == errno);
I've tried both
sem_open(name, O_CREAT | O_EXCL);
and
sem_open(name, O_CREAT | O_EXCL, S_IWUSR | S_IRUSR | S_IRGRP | S_IROTH, 0);
to open the semaphore, but get the same result with each. What am I missing?
EDIT: the version above with only two parameters is wrong- the man page says that when including O_CREAT, you must provide all 4 parameters.
EDIT2: errno is only valid when the function returns an error code. In this case, I should have looked at errno only when sem_open returned SEM_FAILED. I didn't do this, and was examining errno when a perfectly good semaphore had been returned. Problem solved.