Despite a careful read of the related standard documentation, I can't understand what's the expected behavior in POSIX compliant systems when a open
system call is invoked with flags including O_CREAT|O_DIRECTORY
.
The standard specifies that
If O_CREAT and O_DIRECTORY are set and the requested access mode is neither O_WRONLY nor O_RDWR, the result is unspecified.
However it does not specify the behavior of the system with neither (O_CREAT|O_DIRECTORY|O_WRONLY)
nor (O_CREAT|O_DIRECTORY|O_RDWR)
. Indeed (as far as I can understand) the behavior on EISDIR
only apply to existing directories.
In the section related to O_CREATE, the standard specifies that, when the named file does not exist,
if O_DIRECTORY is not set the file shall be created as a regular file; [...]
but again it does not specify what will happen if O_DIRECTORY
is set too.
I've looked the manual pages of both NetBSD (which notoriously cares a lot about POSIX compliance) and Linux (which is a widely used system, despite not actually a POSIX one) but I can't find any clarification.
Is it correct to say that the use of both flags is unspecified? And if so, what's the most common behavior?
Is open(name, O_CREAT|O_DIRECTORY, mode)
equivalent to mkdir
on any POSIX compliant OS?
O_RDONLY
,O_WRONLY
, andO_RDWR
in the open flags (or possiblyO_EXEC
orO_SEARCH
). Historically, omitting those is equivalent to specifyingO_RDONLY
(it is normally 0;O_WRONLY
is normally 1, andO_RDWR
is normally 2), but these are not bit values. (TheO_EXEC
andO_SEARCH
options specified by POSIX complicate life, but neither Linux (Ubuntu 16.04 LTS) nor macOS 10.12.6 supports either of them.) I see now where I got my 'faulty' code from — I copied youropen()
command without realizing I wasn't strictly abiding by the rules. – Wishfulopen()
, it says: In addition, theopen()
function refuses to open non-directories if the O_DIRECTORY flag is set. This avoids race conditions whereby a user might compromise the system by substituting a hard link to a sensitive file (e.g., a device or a FIFO) while a privileged application is running, where opening a file even for read access might have undesirable side-effects. – Wishful