race-condition - 检查文件是否存在然后创建文件时如何避免竞争条件?

标签 race-condition systems-programming

我在考虑我的代码中的极端情况,我不知道如何在检查文件是否存在时避免问题,如果不存在,则创建一个具有该文件名的文件。代码大致如下所示:

// 1
status = stat(filename);
if (!status) {
  // 2
  create_file(filename);
}

在调用 1 和 2 之间,另一个进程可以创建文件名。如何避免这个问题,是否有针对此类问题的通用解决方案?它们经常发生在系统编程中。

最佳答案

这就是 O_EXCL | open() 的 O_CREAT 标志设计用于:

If O_CREAT and O_EXCL are set, open() shall fail if the file exists. The check for the existence of the file and the creation of the file if it does not exist shall be atomic with respect to other threads executing open() naming the same filename in the same directory with O_EXCL and O_CREAT set. If O_EXCL and O_CREAT are set, and path names a symbolic link, open() shall fail and set errno to [EEXIST], regardless of the contents of the symbolic link. If O_EXCL is set and O_CREAT is not set, the result is undefined.

所以:

fd = open(FILENAME, O_EXCL | O_CREAT | O_RDWR);
if (fd <0) { /* file exists or there were problems like permissions */
    fprintf(stderr, "open() failed: \"%s\"\n", strerror(errno));
    abort();
}
 /* file was newly created */

关于race-condition - 检查文件是否存在然后创建文件时如何避免竞争条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24712383/

相关文章:

c - 如何捕获SIGINT并在子进程中忽略它?

Java:使代码块原子化

.net - 方法内联优化会导致竞争条件吗?

c - 为什么使用 mmap 和 madvise 顺序逐行读取大文件比 fgets 慢?

memory-management - 有关N路集合关联缓存步骤的信息

c - sigaction系统调用: what if sa_mask includes one of the blocked signals?

c++ - Drd - 如何解释这个 "Other segment"调用堆栈?

c - 具有静态变量的信号处理程序中的竞争条件

c - 尝试手动触发竞争条件时 ln 失败

memory-management - 如何划分分配区域,以便可以分别重新分配两个区域?