Is there any way on a POSIX system to atomically create a directory only if it doesn't already exist?
Similar to
int fd = open( "/path/to/file", O_CREAT | O_EXCL | O_RDWR, 0644 );
This doesn't work:
int dfd = open( "/path/to/dir", O_DIRECTORY | O_CREAT | O_EXCL | O_RDWR, 0755 );
fails on my Solaris 11 and Ubuntu 20.04 systems with errno set to EINVAL on Solaris and ENOTDIR on Ubuntu.
The POSIX open() documentation states this for O_CREAT:
If the file exists, this flag has no effect except as noted under
O_EXCLbelow. Otherwise, ifO_DIRECTORYis not set ...
Well, it's not a file, and O_DIRECTORY is set.
(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.)