is_regular_file后我有什么保证

What guarantee do I have after is_regular_file?

本文关键字:什么 regular file is      更新时间:2023-10-16

考虑一个boost::filesystem::path p,是否可以同时boost::filesystem::is_regular_file(p) == truestd::ifstream(p.c_str()).is_open() == false?如果是,在哪种情况下?

上下文是为比较函数编写断言:

bool identical_files(const boost::filesystem::path& p1, const boost::filesystem::path& p2)
{
  assert(boost::filesystem::is_regular_file(p1));
  assert(boost::filesystem::is_regular_file(p2));
  std::ifstream f1(p1.c_str());
  assert(f1.is_open()); // IS THIS REDUNDANT ???
  std::ifstream f2(p2.c_str());
  assert(f2.is_open());
  // ...
  // ...
  // ...
}

您唯一的保证是在调用时,路径是常规文件。由于文件系统隐式是一种争用条件,因此 boost::filesystem::is_regular_file(p1)std::ifstream f1(p1.c_str()) 之间的调用实际上可能引用两个不同的对象

考虑以下场景:

  • 进程 1 调用boost::filesystem::is_regular_file(p1) ,成功并确定它是一个"正常"文件
  • 进程 2 删除 p1 指向的路径
  • 进程 1 调用std::ifstream f1(p1.c_str()),但无法打开文件

你能在这里看到竞争条件吗?