我想执行一个生成 txt 文件的 exe,并在另一个脚本中执行,然后检查 txt 文件是否已创建。
在 xampp 中,我只是将 test.txt 文件拖到以下 php 脚本目录中,但它似乎无法正常工作,而且如果我将 text.txt 添加到目录并启动脚本而不是在它之前启动添加然后第二个回声似乎永远不会发生。
如何让 PHP 等待文本文件存在然后继续?
set_time_limit(0);
echo "Script began: " . date("d-m-Y h:i:s") . "<br>";
$status = file_exists("test.txt");
while($status != true) {
if ($status == true) {
echo "The file was found: " . date("d-m-Y h:i:s") . "<br>";
break;
}
}
这也行不通:
set_time_limit(0);
echo "Script began: " . date("d-m-Y h:i:s") . "<br>";
while(!file_exists("test.txt")) {
if (file_exists("test.txt")) {
echo "The file was found: " . date("d-m-Y h:i:s") . "<br>";
break;
}
}
我相信您有其他保护措施来确保您不会陷入无限循环。
while(!file_exists('test.txt'));
echo "The file was found: " . date("d-m-Y h:i:s") . "<br>";
会更简单。
无论如何,你的问题在于你的预测试。既然一开始就失败了,那么就永远不会重复。您需要的是事后测试:
do {
if (file_exists("test.txt")) {
printf('The file was found: %s', date("d-m-Y h:i:s"));
break;
}
sleep(1); // or whatever …
} while(!file_exists("test.txt"));
这应该可以正常工作
set_time_limit(0);
echo "Script began: " . date("d-m-Y h:i:s") . "<br>";
do {
if (file_exists("test.txt")) {
echo "The file was found: " . date("d-m-Y h:i:s") . "<br>";
break;
}
} while(true);
我想你应该使用这种方法:
set_time_limit(0);
echo "Script began: " . date("d-m-Y h:i:s") . "<br>";
while (true) {
// we will always check for file existence at least one time
// so if `test.txt` already exists - you will see the message
// if not - script will wait until file appears in a folder
if (file_exists("test.txt")) {
echo "The file was found: " . date("d-m-Y h:i:s") . "<br>";
break;
}
}
简短的实验表明,等待异步文件系统更改(使用 PHP 作为 Apache 中的模块)必须在循环中产生控制。否则,等待的循环数(例如通过 unlink() 删除文件)似乎在很大的范围内是随机的。在这样的循环中让出可以通过“usleep(250000)”来完成,这将让出控制 1/4 秒。