简体   繁体   English

sem_open 在 linux 下返回 0

[英]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.这打印出 0:未创建信号量。 What am I doing wrong?我究竟做错了什么? I tested this code on an OSX environment and it worked perfectly.我在 OSX 环境中测试了这段代码,它运行良好。

The Linux manpage for sem_open says (emphasis added): sem_open的Linux sem_open说(强调):

ENOENT The O_CREAT flag was not specified in oflag and no semaphore with this name exists; ENOENT在oflag中未指定O_CREAT标志,并且不存在具有该名称的信号灯; or, O_CREAT was specified, but name wasn't well formed . 或者,已指定O_CREAT但名称格式不正确

The sem_overview says this about semaphore names: sem_overview表示有关信号量名称的信息:

A named semaphore is identified by a name of the form /somename ; 命名信号量由/somename形式的名称/somename that is, a null-terminated string of up to NAME_MAX-4 (ie, 251) characters consisting of an initial slash, followed by one or more characters, none of which are slashes. 也就是说,一个以NULL结尾的字符串,最多NAME_MAX-4 (即251个)字符,由一个初始斜杠组成,后跟一个或多个字符,都不是斜杠。

I had similar problem starting from GLIBC version 2.34.从 GLIBC 2.34 版开始,我遇到了类似的问题。

sem_open returned always NULL and error code was set to ENOENT (2). sem_open始终返回NULL并且错误代码设置为ENOENT (2)。

The problem was, that on my Linux system there was no /dev/shm directory.问题是,在我的 Linux 系统上没有/dev/shm目录。 Starting from GLIBC version 2.34, this folder is a requirement to use shared semaphores.从 GLIBC 版本 2.34 开始,此文件夹是使用共享信号量的要求。

From the documentation at http://pubs.opengroup.org/onlinepubs/009695399/functions/sem_open.html 来自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. 如果name以斜杠字符开头,则使用相同name值调用sem_open()的进程应引用相同的信号量对象,只要该名称没有被删除即可。 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 /. sem_open()函数的实现者可以定义如果名称不以/开头的情况。 It appears that linux doesn't allow such names. 看来linux不允许这样的名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM