文件锁

最后更新于:2022-04-02 04:27:58

## 文件锁 ### 锁可重入性: 1. 进程内可重入 2. 子进程内可重入 ```php $fp = fopen('./s-lock.lock', 'r'); if (flock($fp, LOCK_EX | LOCK_NB)) echo 'lock ok 1' . PHP_EOL; if (flock($fp, LOCK_EX | LOCK_NB)) echo 'lock ok 2' . PHP_EOL; // 同一个进程内可重入 $r = pcntl_fork(); if ($r > 0) { if (flock($fp, LOCK_EX | LOCK_NB)) echo 'lock ok 3' . PHP_EOL; } elseif ($r == 0) { if (flock($fp, LOCK_EX | LOCK_NB)) echo 'lock ok 4' . PHP_EOL; if (flock($fp, LOCK_EX | LOCK_NB)) echo 'lock ok 5' . PHP_EOL; } else { echo 'fork fail'; } sleep(5); ``` ~~~shell $: php test.php lock ok 1 lock ok 2 lock ok 3 lock ok 4 lock ok 5 ~~~
';