$pid = posix_getpid();
try {
#$fp = new SplFileObject("./flock.pid", "w+");
$fp = fopen("./flock.pid", 'r+');
echo print_r($fp, true).PHP_EOL;
echo "is_resource:".json_encode(is_resource($fp)).PHP_EOL;
echo "pid:".$pid.PHP_EOL;
$bRet = flock($fp, LOCK_EX | LOCK_NB, $wblock);
echo "{$pid}| sleep(5) ....".PHP_EOL;
sleep(5);
echo "{$pid}|bRet:".json_encode($bRet)."|wblock:".json_encode($wblock).PHP_EOL;
if($bRet) {
fwrite($fp, "pid:".posix_getpid());
}
fclose($fp);
echo "is_resource:".json_encode(is_resource($fp)).PHP_EOL;
$bRet = flock($fp, LOCK_EX | LOCK_NB, $wblock);
echo "{$pid}| sleep(5) ....".PHP_EOL;
echo "sleep(5) 2 ...".PHP_EOL;
sleep(5);
echo "{$pid} | done ...".PHP_EOL;
} catch(Exception $err) {
echo "{$pid}|Exception:".$err->getMessage().PHP_EOL;
try {
#$fp = new SplFileObject("./flock.pid", "w+");
$fp = fopen("./flock.pid", 'r+');
echo print_r($fp, true).PHP_EOL;
echo "is_resource:".json_encode(is_resource($fp)).PHP_EOL;
echo "pid:".$pid.PHP_EOL;
$bRet = flock($fp, LOCK_EX | LOCK_NB, $wblock);
echo "{$pid}| sleep(5) ....".PHP_EOL;
sleep(5);
echo "{$pid}|bRet:".json_encode($bRet)."|wblock:".json_encode($wblock).PHP_EOL;
if($bRet) {
fwrite($fp, "pid:".posix_getpid());
}
fclose($fp);
echo "is_resource:".json_encode(is_resource($fp)).PHP_EOL;
$bRet = flock($fp, LOCK_EX | LOCK_NB, $wblock);
echo "{$pid}| sleep(5) ....".PHP_EOL;
echo "sleep(5) 2 ...".PHP_EOL;
sleep(5);
fwrite($fp, "pid:".posix_getpid());
fflush($fp); // flush output before releasing the lock
flock($fp, LOCK_UN);
echo "{$pid} | done ...".PHP_EOL;
} catch(Exception $err) {
echo "{$pid}|Exception:".$err->getMessage().PHP_EOL;
}
未设置LOCK_NB 则wblock返回0
flcose($fp) 后 fwrite和flock都会报warning错误 且flock返回false wblock返回”“