如果目录不存在,是否可以在 POSIX 系统上自动创建目录? [英] Is there a way on a POSIX system to atomically create a directory if it doesn't exist?
问题描述
在 POSIX 系统上有没有办法在目录不存在时自动创建目录?
Is there any way on a POSIX system to atomically create a directory only if it doesn't already exist?
类似
int fd = open( "/path/to/file", O_CREAT | O_EXCL | O_RDWR, 0644 );
这不起作用:
int dfd = open( "/path/to/dir", O_DIRECTORY | O_CREAT | O_EXCL | O_RDWR, 0755 );
在我的 Solaris 11 和 Ubuntu 20.04 系统上失败,errno
在 Solaris 上设置为 EINVAL
,在 Ubuntu 上设置为 ENOTDIR
.
fails on my Solaris 11 and Ubuntu 20.04 systems with errno
set to EINVAL
on Solaris and ENOTDIR
on Ubuntu.
POSIX open()
文档 为 O_CREAT
声明:
如果文件存在,则此标志无效,除非在下面的 O_EXCL
下注明.否则,如果 O_DIRECTORY
未设置 ...
If the file exists, this flag has no effect except as noted under
O_EXCL
below. Otherwise, ifO_DIRECTORY
is not set ...
好吧,它不是一个文件,并且 O_DIRECTORY
已设置.
Well, it's not a file, and O_DIRECTORY
is set.
(灵感来自问题比赛条件统计和 mkdir - 如果目录不存在,POSIX 中似乎没有任何方法可以自动创建目录.)
(Inspired by the question Race condition stat and mkdir - there doesn't appear to be any way in POSIX to atomically create a directory if it doesn't already exist.)
推荐答案
要回答标题中的问题,mkdir 会这样做——不需要额外的标志,因为 mkdir 将始终原子地"创建一个目录,当且仅当它不存在(且路径不是文件).
To answer the question in your title, mkdir does this -- there's no need for extra flags as mkdir will always "atomically" create a directory if and only if it does not exist (and the path is not a file).
从评论看来,您实际上想以原子方式创建并打开一个目录,但这似乎是一个 XY 问题.为什么,因为无论如何您都无法打开目录进行写入?如果您首先创建然后(非原子地)打开目录,那么行为上没有区别(并且没有竞争条件),就好像在此期间有人删除了目录,打开将失败.
From comments, it seems that you actually want to atomically create and open a directory, but it seems like this is an XY problem. Why, as you cannot open a directory for write in any case? If you first create and then open the directory (non-atomically) then there is no difference in behavior (and no race condition) as if in the interim, someone removed the directory, the open will fail.
如果您担心只在设置了权限的目录中创建文件而其他人无法读取它们,您可以在打开目录后检查该目录的权限和所有权(使用 fstat).
If you're worried about only creating files in a directory with permissions set such that noone (else) can read them, you can check the permissions and ownership of the directory (with fstat) after opening it.
这篇关于如果目录不存在,是否可以在 POSIX 系统上自动创建目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!