Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sem_open returns 0 under linux

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.

like image 248
Matteo Monti Avatar asked Jun 10 '26 06:06

Matteo Monti


1 Answers

The Linux manpage for sem_open says (emphasis added):

ENOENT The O_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 to NAME_MAX-4 (i.e., 251) characters consisting of an initial slash, followed by one or more characters, none of which are slashes.

like image 115
Mat Avatar answered Jun 14 '26 03:06

Mat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!