sem_open returns 0 下 linux

sem_open returns 0 under linux

这听起来像是一个微不足道的问题,但我无法轻易找到解决方案。

这是我的代码:

#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;
}

这会打印出 0:未创建信号量。我究竟做错了什么?我在 OSX 环境中测试了这段代码,它运行良好。

sem_open 的 Linux 联机帮助页说(强调):

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.

sem_overview 关于信号量名称是这样说的:

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.

来自 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.

sem_open() 函数的实现者可以定义如果名称不以 / 开头会发生什么。 linux 似乎不允许这样的名称。

我从 GLIBC 2.34 版开始遇到了类似的问题。

sem_open 总是返回 NULL 并且错误代码设置为 ENOENT (2).

问题是,在我的 Linux 系统上没有 /dev/shm 目录。从 GLIBC 版本 2.34 开始,此文件夹是使用共享信号量的要求。