(PHP 4, PHP 5, PHP 7, PHP 8)
flock — 輕便的咨詢(xún)文件鎖定
$handle
, int $operation
, int &$wouldblock
= ?): boolflock() 允許執行一個(gè)簡(jiǎn)單的可以在任何平臺中使用的讀取/寫(xiě)入模型(包括大部分的 Unix 派生版和甚至是 Windows)。
在 PHP 5.3.2版本之前,鎖也會(huì )被 fclose() 釋放(在腳本結束后會(huì )自動(dòng)調用)。
PHP 支持以咨詢(xún)方式(也就是說(shuō)所有訪(fǎng)問(wèn)程序必須使用同一方式鎖定, 否則它不會(huì )工作)鎖定全部文件的一種輕便方法。
默認情況下,這個(gè)函數會(huì )阻塞到獲取鎖;這可以通過(guò)下面文檔中 LOCK_NB
選項來(lái)控制(在非 Windows 平臺上)。
handle
文件系統指針,是典型地由 fopen() 創(chuàng )建的 resource(資源)。
operation
operation
可以是以下值之一:
LOCK_SH
取得共享鎖定(讀取的程序)。
LOCK_EX
取得獨占鎖定(寫(xiě)入的程序。
LOCK_UN
釋放鎖定(無(wú)論共享或獨占)。
如果不希望 flock() 在鎖定時(shí)堵塞,則是
LOCK_NB
(Windows 上還不支持)。
wouldblock
如果鎖定會(huì )堵塞的話(huà)(EWOULDBLOCK
錯誤碼情況下),可選的第三個(gè)參數會(huì )被設置為 true
。(Windows 上不支持)
成功時(shí)返回 true
, 或者在失敗時(shí)返回 false
。
版本 | 說(shuō)明 |
---|---|
5.3.2 | 在文件資源句柄關(guān)閉時(shí)不再自動(dòng)解鎖?,F在要解鎖必須手動(dòng)進(jìn)行。 |
4.0.1 |
增加了常量 LOCK_XXX 。
之前你必須使用 1 代表 LOCK_SH ,2 代表
LOCK_EX ,3 代表LOCK_UN ,4 代表
LOCK_NB 。
|
示例 #1 flock() 例子
<?php
$fp = fopen("/tmp/lock.txt", "r+");
if (flock($fp, LOCK_EX)) { // 進(jìn)行排它型鎖定
ftruncate($fp, 0); // truncate file
fwrite($fp, "Write something here\n");
fflush($fp); // flush output before releasing the lock
flock($fp, LOCK_UN); // 釋放鎖定
} else {
echo "Couldn't get the lock!";
}
fclose($fp);
?>
示例 #2 flock() 使用 LOCK_NB
選項
<?php
$fp = fopen('/tmp/lock.txt', 'r+');
/* Activate the LOCK_NB option on an LOCK_EX operation */
if(!flock($fp, LOCK_EX | LOCK_NB)) {
echo 'Unable to obtain lock';
exit(-1);
}
/* ... */
fclose($fp);
?>
注意:
flock() uses mandatory locking instead of advisory locking on Windows. Mandatory locking is also supported on Linux and System V based operating systems via the usual mechanism supported by the fcntl() system call: that is, if the file in question has the setgid permission bit set and the group execution bit cleared. On Linux, the file system will also need to be mounted with the mand option for this to work.
注意:
由于 flock() 需要一個(gè)文件指針, 因此可能不得不用一個(gè)特殊的鎖定文件來(lái)保護打算通過(guò)寫(xiě)模式打開(kāi)的文件的訪(fǎng)問(wèn)(在 fopen() 函數中加入 "w" 或 "w+")。
注意:
May only be used on file pointers returned by fopen() for local files, or file pointers pointing to userspace streams that implement the streamWrapper::stream_lock() method.
Assigning another value to handle
argument in
subsequent code will release the lock.
在部分操作系統中 flock() 以進(jìn)程級實(shí)現。當用一個(gè)多線(xiàn)程服務(wù)器 API(比如 ISAPI)時(shí),可能不可以依靠 flock() 來(lái)保護文件,因為運行于同一服務(wù)器實(shí)例中其它并行線(xiàn)程的 PHP 腳本可以對該文件進(jìn)行處理。
flock() 不支持舊的文件系統,如 FAT
以及它的派生系統。因此,此環(huán)境下總是返回 false
(尤其是對 Windows 98 用戶(hù)來(lái)說(shuō))。