I'm thinking of corner cases in my code and I can't figure out how to avoid problem when you check if file exists, and if it does not, you create a file with that filename. The code approximately looks like this:
// 1
status = stat(filename);
if (!status) {
// 2
create_file(filename);
}
Between the call to 1 and 2 another process could create the filename. How to avoid this problem and is there a general solution to this type of problems? They happen often in systems programming.
You're supposed to create the file anyway, and let the OS know whether or not you want a new file to be created in the process if the file doesn't already exist. You shouldn't perform a separate check before.
This is what the
O_EXCL | O_CREAT
flags toopen()
were designed for:So: