为什么先调用shm_unlink再调用shm_open?
Why call shm_unlink first before calling shm_open?
我在遗留项目中看到了以下代码模式:
检查是否创建了名为“/abc”的共享内存:
int fd = shm_open("/abc", O_RDWR, 0777);
if(fd != -1)
{
close(fd);
return -1;
}
删除先前由 shm_open()
:
创建的对象
shm_unlink("/abc");
创建共享内存对象:
fd = shm_open("/abc", (O_CREAT | O_RDWR), S_IWUSR);
步骤 2 是否多余?
代码可以 运行 进入第 2 步,因为“/abc”的共享内存对象不存在。换句话说,代码 returns 如果对象确实存在。为什么我们要显式调用 shm_unlink 来删除不存在的对象?
我们可以将三个步骤缩短为一个吗?
我想我们可以按如下进行,我们使用标志O_EXCL
检查是否存在旧内存对象,如果根本不存在则创建它。 shm_open()
手册页说:
O_EXCL
If O_CREAT
was also specified, and a shared memory object
with the given name already exists, return an error. The
check for the existence of the object, and its creation if
it does not exist, are performed atomically.
所以把上面所有代码换成一行应该没问题:
int fd = shm_open("/abc", O_RDWR | O_EXCL, 0777);
对吗?
Is the Step 2 redundant?
是的。它没有任何用处。
此外 "check-for-existence" 容易出现 TOCTOU 漏洞。
Can we shorten the 3-step above as a single step
是的。这才是正确的做法。但是您还需要 O_CREAT
标志(您的代码中缺少该标志)。
我在遗留项目中看到了以下代码模式:
检查是否创建了名为“/abc”的共享内存:
int fd = shm_open("/abc", O_RDWR, 0777); if(fd != -1) { close(fd); return -1; }
删除先前由
创建的对象shm_open()
:shm_unlink("/abc");
创建共享内存对象:
fd = shm_open("/abc", (O_CREAT | O_RDWR), S_IWUSR);
步骤 2 是否多余?
代码可以 运行 进入第 2 步,因为“/abc”的共享内存对象不存在。换句话说,代码 returns 如果对象确实存在。为什么我们要显式调用 shm_unlink 来删除不存在的对象?
我们可以将三个步骤缩短为一个吗?
我想我们可以按如下进行,我们使用标志O_EXCL
检查是否存在旧内存对象,如果根本不存在则创建它。 shm_open()
手册页说:
O_EXCL
If O
_CREAT
was also specified, and a shared memory object with the given name already exists, return an error. The check for the existence of the object, and its creation if it does not exist, are performed atomically.
所以把上面所有代码换成一行应该没问题:
int fd = shm_open("/abc", O_RDWR | O_EXCL, 0777);
对吗?
Is the Step 2 redundant?
是的。它没有任何用处。
此外 "check-for-existence" 容易出现 TOCTOU 漏洞。
Can we shorten the 3-step above as a single step
是的。这才是正确的做法。但是您还需要 O_CREAT
标志(您的代码中缺少该标志)。