高负载系统中File_exists


file_exists on high load system

代码:

$tmp_file_path = '/path/to/tmp/file';
// move file from tmp dir
$new_file_path = '/path/to/new/location/file';
while(file_exists($new_file_path)){
  $new_file_path = $new_file_path . microtime(true);
  usleep(100000);
}
// HERE ANOTHER INSTANCE OF THIS SCRIPT COULD HAVE ALREADY TAKEN NEW NAME,
// $new_file_path
// BUT NEXT CALL TO rename function OVERWRITES IT WITH NEW CONTENT!
rename($tmp_file_path, $new_file_path ); //Attempts to rename oldname to newname,
// moving it between directories if necessary. If newname exists, it will be
// overwritten. 

在PHP中有什么解决方案使file_exists函数创建一个文件,如果它不存在,像touch一样,在一个原子操作中?

PHP有tempnam函数:

// create a file with unique name in $new_file_path
$new_file_path = '/path/to/new/location';
$tmpfname = tempnam($new_file_path, "foo");

根据手册:

tempnam创建一个具有唯一文件名的文件,访问权限设置为0600,在指定的目录下。如果目录不存在,tempnam()可能会在系统的临时目录中生成一个文件,并且返回它的名称