Home > Enterprise >  sem_open with initial value of 0 failing with EINVAL
sem_open with initial value of 0 failing with EINVAL

Time:08-26

I have this simple example which I've run on Linux:

#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>

#include <semaphore.h>

#define SEM_NAME "/some/sem/name"

int main() {
    sem_t *sem;

    sem = sem_open(SEM_NAME, O_CREAT, S_IRUSR, 0);
    if ( sem == SEM_FAILED ) {
        perror("sem_open");
        return 1;
    }

    sem_close(sem);
    sem_unlink(SEM_NAME);
    return 0;
}

Its output is

sem_open: Invalid argument

Here are the possible causes of EINVAL as listed by the man page:

EINVAL: value was greater than SEM_VALUE_MAX.

EINVAL: name consists of just "/", followed by no other characters.

In my example, value is 0 and name is clearly not just "/". What am I missing?

CodePudding user response:

Per the POSIX sem_open() documentation:

... The name argument conforms to the construction rules for a pathname, except that the interpretation of <slash> characters other than the leading <slash> character in name is implementation-defined, and that the length limits for the name argument are implementation-defined and need not be the same as the pathname limits {PATH_MAX} and {NAME_MAX}. If name begins with the <slash> character, then processes calling sem_open() with the same value of name shall refer to the same semaphore object, as long as that name has not been removed. If name does not begin with the <slash> character, the effect is implementation-defined.

Assuming you're on a Linux system, the Linux sem_open() man page]() states:

sem_open() creates a new POSIX semaphore or opens an existing semaphore. The semaphore is identified by name. For details of the construction of name, see sem_overview(7).

The sem_overview(7) man page states:

Named semaphores

A named semaphore is identified by a name of the form /somename; that is, a null-terminated string of up to NAME_MAX-4 (i.e., 251) characters consisting of an initial slash, followed by one or more characters, none of which are slashes.

Note the bolded part: "none of which are slashes".

Your

#define SEM_NAME "/some/sem/name"

defines an invalid semaphore name.

  • Related