This sounds like a trivial question, but I couldn't easily find a solution around.
Here is my code:
#include <iostream>
#include <fcntl.h>
#include <semaphore.h>
using namespace std;
int main()
{
sem_t * my_semaphore = sem_open("./my_semaphore", O_CREAT, 0755, 1);
cout<<my_semaphore<<endl;
}
This prints out 0: the semaphore wasn't created. What am I doing wrong? I tested this code on an OSX environment and it worked perfectly.
The Linux manpage for sem_open
says (emphasis added):
ENOENT
TheO_CREAT
flag was not specified in oflag and no semaphore with this name exists; or,O_CREAT
was specified, but name wasn't well formed .
The sem_overview
says this about semaphore names:
A named semaphore is identified by a name of the form
/somename
; that is, a null-terminated string of up toNAME_MAX-4
(ie, 251) characters consisting of an initial slash, followed by one or more characters, none of which are slashes.
I had similar problem starting from GLIBC version 2.34.
sem_open
returned always NULL
and error code was set to ENOENT
(2).
The problem was, that on my Linux system there was no /dev/shm
directory. Starting from GLIBC version 2.34, this folder is a requirement to use shared semaphores.
From the documentation at http://pubs.opengroup.org/onlinepubs/009695399/functions/sem_open.html
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. The interpretation of slash characters other than the leading slash character in name is implementation-defined.
Implementors of the sem_open() function can define what happens if the name doesn't start with a /. It appears that linux doesn't allow such names.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.