shmget 上没有 IPC_EXCL 的 EEXIST
我在共享内存方面遇到了一个奇怪的问题。
方法 shmget
返回 -1,并且 errno
设置为 EEXIST
。根据 man 的说法,只有当同时提供标志 IPC_EXCL
和 IPC_CREAT
时才有可能。
我的代码:
int main()
{
int shmid = shmget(0xABCD, MAX_SIZE, IPC_CREAT | 0x660);
int shmid2 = shmget(0xABCD, MAX_SIZE, IPC_CREAT | 0x660 );
if(shmid == -1)
{
if(errno == EEXIST)
perror("Error");
return -1;
}
if(shmid2 == -1)
{
if(errno == EEXIST)
perror("Error2");
return -1;
}
shmctl(shmid, IPC_RMID, NULL);
return 0;
}
它使用 -Wall 进行编译,没有警告,我使用 ipcs 检查该段是否已经存在(如果需要,则将其删除)。输出为错误2:文件存在
。 当我将第二个 shmget 更改为:
int shmid2 = shmget(0xABCD, MAX_SIZE, 0 );
引自 man shmget
:
EEXIST IPC_CREAT | IPC_EXCL was specified and the segment exists.
还有一个问题:尝试执行 shmget 时不使用 mode_flags (即 0x660)是真的吗?
I have a strange problem with shared memory.
Method shmget
returns -1 and errno
is set to EEXIST
. According to man, it is only possible when both flag IPC_EXCL
and IPC_CREAT
are provided.
My code:
int main()
{
int shmid = shmget(0xABCD, MAX_SIZE, IPC_CREAT | 0x660);
int shmid2 = shmget(0xABCD, MAX_SIZE, IPC_CREAT | 0x660 );
if(shmid == -1)
{
if(errno == EEXIST)
perror("Error");
return -1;
}
if(shmid2 == -1)
{
if(errno == EEXIST)
perror("Error2");
return -1;
}
shmctl(shmid, IPC_RMID, NULL);
return 0;
}
It compiles with -Wall without warnings, I check with ipcs if the segment is already present (and remove it if needed). The output is Error2: File exists
.
It works when I change the second shmget to:
int shmid2 = shmget(0xABCD, MAX_SIZE, 0 );
Quote from man shmget
:
EEXIST IPC_CREAT | IPC_EXCL was specified and the segment exists.
And one more question: is it true, that mode_flags (i.e. 0x660) are not used when trying to execute shmget?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
权限模式需要以八进制指定,而不是十六进制。
0x660
(十六进制)=03140
(八进制)。并且IPC_EXCL
标志在 Linux ABI 中具有八进制值02000
- 因此可以使用0x660
而不是0660
您不小心设置了IPC_EXCL
,这就是您收到错误的原因。如果我将程序中的两个实例
0x660
更改为0660
并修复其他导致其无法编译的问题(特别是,您遗漏了所有标头和0660
的定义) code>MAX_SIZE)它按预期工作。Permission modes need to be specified in octal, not hexadecimal.
0x660
(hex) =03140
(octal). And theIPC_EXCL
flag has the octal value02000
in the Linux ABI -- so by using0x660
instead of0660
you are accidentally settingIPC_EXCL
, which is why you get the error.If I change both instances of
0x660
to0660
in your program and fix the other things that make it not compile (notably, you left out all the headers and the definition ofMAX_SIZE
) it works as expected.