-
-
Save wolf432/175b2b33b66a5bb68add24534e2685ef to your computer and use it in GitHub Desktop.
php写文件,带超时处理
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 写入文件,超时则写入失败 | |
* | |
* @param mixed $fileName 文件名 | |
* @param mixed $text 要写入的内容 | |
* @param int $timeOut 等待锁的超时时间 | |
* @param string $mode 文件操作类型,同fopen的model参数一致 | |
* @return boolean | |
*/ | |
function swrite($fileName, $text, $timeOut = 1, $mode = 'a') | |
{ | |
$fp = fopen($fileName, $mode); | |
if ($fp == false) | |
return false; | |
$stime = explode(" ",microtime()); | |
$canWrite = false; | |
do | |
{ | |
$etime = explode(" ",microtime()); | |
//尝试获取文件锁 | |
$canWrite = flock($fp, LOCK_EX | LOCK_NB); | |
usleep(500000); | |
}while(!$canWrite && ($etime[1] - $stime[1]) < $timeOut); //如果获取锁失败则循环获取,直到超过超时时间。 | |
if ($canWrite) | |
{ | |
fwrite($fp, $text); | |
//释放锁 | |
flock($fp, LOCK_UN); | |
} | |
fclose($fp); | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment