写入文件和mkdir竞争条件C [英] Writing to file and mkdir race conditions C

查看:187
本文介绍了写入文件和mkdir竞争条件C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做了一个尝试创建目录的函数,然后编写了一个简单文件:

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.

我读到,如果另一个进程使用写入权限打开了同一文件,则打开"将失败.但是,这是真的吗?
如果我同时运行此代码的多个实例,那么mkdir和写入操作会怎样?

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?

推荐答案

该手册页指出,如果目录已经存在,则mkdir失败.它返回-1而不是0.如果忽略它,则只要a/b/c/d实际上是目录,您的代码通常就可以正常工作.竞争过程可能会将它们创建为其他事物,从而导致错误.目前尚不清楚为什么要使用模式0777,因为将0700甚至0770与特殊组一起使用会更好.如果您确定它们始终是目录,那么代码的每个实例都将确保dir路径存在,并且唯一的争用将是创建文件.

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.

这篇关于写入文件和mkdir竞争条件C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆