Writing to file and mkdir race conditions C

天大地大妈咪最大 提交于 2019-12-13 04:07:24

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!