问题
I made a function that tries to create a directory, and then write a simple file:
buffer = "Hello world!";
string url = "a/b/c/d/";
string tmp = "";
string done = "";
while((tmp = GetBaseDir(url)).compare("")!=0){
done+=tmp;
mkdir(done.c_str(), 0777);
} // GetBaseDir returns "a/", and changes url to "b/c/d/"
ofstream file;
file.open((url+"file.txt").c_str(),ios::trunc);
file << buffer;
file.close();
As you can see, it only tries, if there is a failure it just keeps going on.
I read that 'open' will fail if another process opened that same file with write permissions. But, is this true?
What happens with mkdir and the write operation if I run several instances of this code at the same time?
回答1:
The man page notes mkdir fails when the directory already exists. It returns -1 rather than 0. If you ignore that, your code will usually work OK, as long as a/b/c/d are actually directories. A competing process could create them as something else, resulting in an error. It's not clear why you use mode 0777, since it would be far better to use 0700 or even 0770 with a special group. If you are sure they will always be directories, then every instance of the code will ensure that the dir path exists, and the only contention will be on creating the file.
NAME
mkdir -- make a directory file
SYNOPSIS
#include <sys/stat.h>
int mkdir(const char *path, mode_t mode);
RETURN VALUES
A 0 return value indicates success. A -1 return value indicates an
error, and an error code is stored in errno.
ERRORS
Mkdir() will fail and no directory will be created if:
...
[EEXIST] The named file exists.
来源:https://stackoverflow.com/questions/14865338/writing-to-file-and-mkdir-race-conditions-c