stat() 和 std::remove() 的使用 - TOCTOU 问题

问题描述 投票:0回答:1

我有以下形式的程序:

stat(check_for_some_file) 
..... 
..... 
..... 
std::remove(remove the same file)  

我能想到的两个解决方案:

  • 一个是在使用 std::remove() 之前再次使用 stat()
  • 另一个是,使用一些文件描述符来检查该文件是否存在来代替 stat()

有没有更好的方法来解决这个问题?谢谢

c++ race-condition
1个回答
0
投票

这种竞争条件的问题在于,理论上,文件总是可以在统计检查和尝试删除文件之间进行更改。这完全取决于您想要使用

stat
来做什么。如果您担心要避免在无法删除已删除的文件的情况下发生错误,那么您可以处理错误,如下所示:

std::error_code err_code;
if (std::filesystem::remove(fileName, err_code)) {
  // the file did exist and we succesfully removed it.
} else {
  // we attempted to remove the file but failed for some reason
  // the reason can be found in err code,it could be no_such_file_or_directory, permission_denied or something else.
}

但是,如果你想使用 stat 检查更复杂的东西,例如检查修改日期,那么你就不走运了。据我所知,没有办法仅删除未修改的文件。如果您想拥有这样的行为,您需要与正在更改文件的任何其他程序协调锁定机制。

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.