Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

sem_open with initial value of 0 failing with EINVAL

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading