3

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.

Community
  • 1
  • 1
leecbaker
  • 3,611
  • 2
  • 35
  • 51

2 Answers2

0

Before trying sem_open, try sem_unlink()

0

name should have a leading slash. Try put a "/" in front of name. ie. sprintf(name, "/xyz_sem_%d", name_counter++);

harryr
  • 106
  • 5
  • 1
    Where is it documented that semaphore names should start with a slash? Is this a convention or a hard requirement? – Duncan C Oct 08 '15 at 13:02
  • Not having OSX handy, Freebsd, 'man sem_open' says .... "This implementation places strict requirements on the value of name: it must begin with a slash (‘/’) and contain no other slash characters. " , On linux the same sort of thing in 'man sem_overview' , so prolly also true for OSX – harryr Nov 05 '15 at 03:51
  • iOS/Mac OS doesn't seem to have that requirement. I'm using semaphores who's names start with an alpha and contain alphanumerics and slashes, and they work fine. – Duncan C Nov 05 '15 at 14:40