Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

open with O_CREAT - was it opened or created?

Tags:

c

file

unix

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".

like image 494
Sergey Avatar asked Apr 03 '13 21:04

Sergey


People also ask

What does O_creat mean?

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.

What is the Oflag used to open a file with the mode read only?

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.

What is the default mode for the open () function?

open() Syntax: Default mode is 'r' for reading. See all the access modes. buffering: (Optional) Used for setting buffering policy.

What is O_excl?

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.


1 Answers

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);
}
like image 81
suspectus Avatar answered Sep 25 '22 13:09

suspectus