[英]How to check if shared memory exists using shmget or ftok?
I am writting project in c using shared memory via shm functions.我正在通过 shm 函数使用共享 memory 在 c 中编写项目。 I want to try to "connect" to shared memory and check if it exists using shmget() function.
我想尝试“连接”到共享 memory 并使用 shmget() function 检查它是否存在。
I tried a few flags with this function but failed to achieve expected result.我用这个 function 尝试了几个标志,但未能达到预期的结果。 I wonder if there is a way to see whether a shared memory already exists.
我想知道是否有办法查看共享的 memory 是否已经存在。
The manual page
spells this out rather explicitly. manual page
相当明确地说明了这一点。
int shmget(key_t key, size_t size, int shmflg);
If shmflg specifies both IPC_CREAT and IPC_EXCL and a shared memory segment already exists for key, then shmget() fails with errno set to EEXIST .
如果shmflg指定了IPC_CREAT和IPC_EXCL并且密钥的共享 memory 段已经存在,则shmget()失败, errno设置为EEXIST 。
And again, the flags:再一次,标志:
IPC_CREAT
IPC_CREAT
- Create a new segment.
创建一个新的细分市场。 If this flag is not used, then shmget() will find the segment associated with key and check to see if the user has permission to access the segment.
如果不使用此标志,则shmget()将查找与key关联的段并检查用户是否有权访问该段。
IPC_EXCL
IPC_EXCL
- This flag is used with IPC_CREAT to ensure that this call creates the segment.
此标志与IPC_CREAT一起使用以确保此调用创建段。 If the segment already exists, the call fails.
如果该段已存在,则调用失败。
Alternatively, if the flag IPC_CREAT
is not specified, and no memory segment exists for the given key
, then shmget
fails and sets errno
to ENOENT
.或者,如果未指定标志
IPC_CREAT
,并且给定key
不存在 memory 段,则shmget
失败并将errno
为ENOENT
。
ENOENT
恩恩
- No segment exists for the given key , and IPC_CREAT was not specified.
给定键不存在段,并且未指定IPC_CREAT 。
So you may want to try something along the lines of所以你可能想尝试一些类似的东西
errno = 0;
if (-1 == shmget(key, size, IPC_CREAT | IPC_EXCL)) {
if (EEXIST == errno) {
/* shared memory already exists */
}
}
or或者
errno = 0;
if (-1 == shmget(key, size, 0)) {
if (ENOENT == errno) {
/* shared memory does not exist */
}
}
On the other hand, ftok(3)
fails for the same reasons as stat(2)
.另一方面,
ftok(3)
失败的原因与stat(2)
相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.