Skip to content

Commit

Permalink
Avoid the race condition if multiple calls to MakeDirs occur simult…
Browse files Browse the repository at this point in the history
…aneously with overlapping paths.

Based on #644.

PiperOrigin-RevId: 421565838
(cherry picked from commit aa8b3c6)
  • Loading branch information
allevato authored and keith committed Jan 22, 2022
1 parent fe45593 commit 218ae09
Showing 1 changed file with 30 additions and 2 deletions.
32 changes: 30 additions & 2 deletions tools/common/file_system.cc
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@
#include <sys/types.h>
#include <unistd.h>

#include <cerrno>
#include <iostream>
#include <string>

#ifdef __APPLE__
Expand Down Expand Up @@ -100,7 +102,13 @@ bool MakeDirs(const std::string &path, int mode) {
struct stat dir_stats;
if (stat(path.c_str(), &dir_stats) == 0) {
// Return true if the directory already exists.
return S_ISDIR(dir_stats.st_mode);
if (S_ISDIR(dir_stats.st_mode)) {
return true;
}

std::cerr << "error: path already exists but is not a directory: "
<< path << "\n";
return false;
}

// Recurse to create the parent directory.
Expand All @@ -109,5 +117,25 @@ bool MakeDirs(const std::string &path, int mode) {
}

// Create the directory that was requested.
return mkdir(path.c_str(), mode) == 0;
if (mkdir(path.c_str(), mode) == 0) {
return true;
}

// Race condition: The above call to `mkdir` could fail if there are multiple
// calls to `MakeDirs` running at the same time with overlapping paths, so
// check again to see if the directory exists despite the call failing. If it
// does, that's ok.
if (errno == EEXIST && stat(path.c_str(), &dir_stats) == 0) {
if (S_ISDIR(dir_stats.st_mode)) {
return true;
}

std::cerr << "error: path already exists but is not a directory: "
<< path << "\n";
return false;
}

std::cerr << "error: could not create directory: " << path
<< " (" << strerror(errno) << ")\n";
return false;
}

0 comments on commit 218ae09

Please sign in to comment.