I have 10 processes which try open the same file more or less at the same time using open(O_CREAT) call, then delete it. Is there any robust way to find out which process actually did create the file and which did open already create file, for instance, if I want to accurately count how many times that file was opened in such scenario.
I guess I could put a global mutex on file open operation, and do a sequence of open() calls using O_CREAT and O_EXCL flags, but that doesn't fit my definition of "robust".
O_CREAT. Indicates that the call to open() has a mode argument. If the file being opened already exists O_CREAT has no effect except when O_EXCL is also specified; see O_EXCL following. If the file being opened does not exist it is created.
Applications must specify exactly one of the first three values (file access modes) below in the value of oflag: O_RDONLY. Open for reading only. O_WRONLY.
open() Syntax: Default mode is 'r' for reading. See all the access modes. buffering: (Optional) Used for setting buffering policy.
The real meaning of O_EXCL is "error if create and file exists" but the name is derived from " EXCL usive", which is a bit misleading though and causes many people to misinterpret that flag. Opening a file with O_EXCL will not give you exclusive access to it as some people incorrectly assume.
Use O_EXCL
flag with O_CREAT
. This will fail if the file exists and errno will be set to EEXIST
. If it does fail
then attempt open again without O_CREAT
and without O_EXCL
modes.
e.g.
int fd = open(path, O_WRONLY | O_CREAT | O_EXCL, 0644);
if ((fd == -1) && (EEXIST == errno))
{
/* open the existing file with write flag */
fd = open(path, O_WRONLY);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With