我在目录中有一个文件,我想每小时替换一个当前版本。我使用shell_exec()
到zcat
文件,解压缩并编写文件的过程大约需要4分钟。在读取和写入之前,我记录了目录中已存在的文件的名称,以便在新文件写完后我可以unlink
。但它不会按照我希望的顺序发生。 PHP正在处理shell_exec
时执行删除。只有在四分钟的空目录后才能看到新写的文件。有什么方法可以推迟删除这个删除或者让它成为读写过程的回调吗?
$log_files = scandir("/cached_logs/");
foreach ($log_files as $key => $val){
//non-secure file to delete
if (preg_match("/^access/", $val)){
$log_to_delete= $val;
}
}
$ssl_command_string = "zcat log." . $datetime . ".gz";
//execute
$ssl_res = shell_exec($ssl_command_string);
//build the local directory and append the new file name with the current $datetime
$cached_ssl_file_name = "/cached_logs/log." . $datetime . ".txt";
//open the file handle
$new_ssl = fopen($cached_ssl_file_name, 'w') or die("can't open file");
//write
fwrite($new_ssl, $ssl_res);
//close
fclose($new_ssl);
unlink("/cached_logs/" . $log_to_delete); //this is defined properly above, I just didn't post it as it's irrelevant to the problem.
编辑: 清除了一些内容并纠正了清除信息导致的语法错误
答案 0 :(得分:1)
听起来像是奇怪的事情发生在我身上。主要原因是AFAIK,shell_exec
阻塞,意味着它将等到它被给出的命令在下一个PHP语句运行之前运行完毕。
我整理了一个最小版本的示例脚本,它对我来说很好。
<?php
$log_file = './my-access.log.gz';
$ssl_command_string = "zcat $log_file";
//execute
$ssl_res = shell_exec($ssl_command_string);
$cached_ssl_file_name = "./my-access.log.txt";
//open the file handle
$new_ssl = fopen($cached_ssl_file_name, 'w') or die("can't open file");
//write
fwrite($new_ssl, $ssl_res);
//close
fclose($new_ssl);
unlink($log_file);
答案 1 :(得分:0)
if(is_resource($new_ssl)){
//Handle still open
fclose($new_ssl);
@unlink("cached_logs/" . $log_to_delete);
}