flock

(PHP 4, PHP 5, PHP 7, PHP 8)

flock輕便的咨詢文件鎖定

說明

flock(resource $handle, int $operation, int &$wouldblock = ?): bool

flock() 允許執(zhí)行一個(gè)簡(jiǎn)單的可以在任何平臺(tái)中使用的讀取/寫入模型(包括大部分的 Unix 派生版和甚至是 Windows)。

在 PHP 5.3.2版本之前,鎖也會(huì)被 fclose() 釋放(在腳本結(jié)束后會(huì)自動(dòng)調(diào)用)。

PHP 支持以咨詢方式(也就是說所有訪問程序必須使用同一方式鎖定, 否則它不會(huì)工作)鎖定全部文件的一種輕便方法。 默認(rèn)情況下,這個(gè)函數(shù)會(huì)阻塞到獲取鎖;這可以通過下面文檔中 LOCK_NB 選項(xiàng)來控制(在非 Windows 平臺(tái)上)。

參數(shù)

handle

文件系統(tǒng)指針,是典型地由 fopen() 創(chuàng)建的 resource(資源)。

operation

operation 可以是以下值之一:

  • LOCK_SH取得共享鎖定(讀取的程序)。
  • LOCK_EX 取得獨(dú)占鎖定(寫入的程序。
  • LOCK_UN 釋放鎖定(無論共享或獨(dú)占)。

如果不希望 flock() 在鎖定時(shí)堵塞,則是 LOCK_NB(Windows 上還不支持)。

wouldblock

如果鎖定會(huì)堵塞的話(EWOULDBLOCK 錯(cuò)誤碼情況下),可選的第三個(gè)參數(shù)會(huì)被設(shè)置為 true。(Windows 上不支持)

返回值

成功時(shí)返回 true, 或者在失敗時(shí)返回 false

更新日志

版本 說明
5.3.2 在文件資源句柄關(guān)閉時(shí)不再自動(dòng)解鎖?,F(xiàn)在要解鎖必須手動(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($fpLOCK_EX)) {  // 進(jìn)行排它型鎖定
    
ftruncate($fp0);      // truncate file
    
fwrite($fp"Write something here\n");
    
fflush($fp);            // flush output before releasing the lock
    
flock($fpLOCK_UN);    // 釋放鎖定
} else {
    echo 
"Couldn't get the lock!";
}

fclose($fp);

?>

示例 #2 flock() 使用 LOCK_NB 選項(xiàng)

<?php
$fp 
fopen('/tmp/lock.txt''r+');

/* Activate the LOCK_NB option on an LOCK_EX operation */
if(!flock($fpLOCK_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è)特殊的鎖定文件來保護(hù)打算通過寫模式打開的文件的訪問(在 fopen() 函數(shù)中加入 "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.

警告

在部分操作系統(tǒng)中 flock() 以進(jìn)程級(jí)實(shí)現(xiàn)。當(dāng)用一個(gè)多線程服務(wù)器 API(比如 ISAPI)時(shí),可能不可以依靠 flock() 來保護(hù)文件,因?yàn)檫\(yùn)行于同一服務(wù)器實(shí)例中其它并行線程的 PHP 腳本可以對(duì)該文件進(jìn)行處理。

flock() 不支持舊的文件系統(tǒng),如 FAT 以及它的派生系統(tǒng)。因此,此環(huán)境下總是返回 false(尤其是對(duì) Windows 98 用戶來說)。