mkdir 函数抛出异常“文件存在”,即使在检查该目录不存在后也是如此


mkdir function throw exception 'File exists' even after checking that directory doesn't exist

我偶然发现了PHP中mkdir函数的每一个奇怪的行为。下面是我的简单代码的示例。

$filepath = '/media/static/css/common.css';
if (!file_exists(dirname($filepath)))
{
   mkdir(dirname($filepath), 0777, TRUE);
}

"媒体"文件夹始终存在。必须创建"媒体"文件夹中的所有文件夹。在处理通用.css文件之前,我想创建一个文件夹"/static/css"。

mkdir 偶尔会抛出异常"文件存在"。如果文件夹不存在,我尝试创建一个文件夹。我认为"文件存在"是一个常见的错误,因此该文件夹存在。

我知道我给你的信息很少,这真的很奇怪。也许你可以给我任何建议,我必须做什么,以及如何测试该错误并找到瓶颈。

服务器:CentOS 6.4 版

谢谢。

这是一种竞争条件情况。你应该做这样的事情:

$filepath = '/media/static/css/common.css';
// is_dir is more appropriate than file_exists here
if (!is_dir(dirname($filepath))) {
    if (true !== @mkdir(dirname($filepath), 0777, TRUE)) {
        if (is_dir(dirname($filepath))) {
            // The directory was created by a concurrent process, so do nothing, keep calm and carry on
        } else {
            // There is another problem, we manage it (you could manage it with exceptions as well)
            $error = error_get_last();
            trigger_error($error['message'], E_USER_WARNING);
        }
    }
}

裁判:

  • https://www.drupal.org/files/1642532-drush-mkdir-race-condition.patch
  • https://github.com/KnpLabs/Gaufrette/blob/master/src/Gaufrette/Adapter/Local.php#L260
  • https://github.com/symfony/symfony/commit/04834521f1298c8fee2704b1c4b1df43b655eb60