超越PHP PHP动态 | 经典文章 | CLASS | 相关下载 | 常见问题 | FORUM | WIKI | 在线手册
Site search:    
<filetypefnmatch>
Last updated: Fri, 22 Jun 2007

flock

(PHP 3>= 3.0.7, PHP 4 , PHP 5)

flock -- 轻便的咨询文件锁定

说明

bool flock ( int handle, int operation [, int &wouldblock])

PHP 支持以咨询方式(也就是说所有访问程序必须使用同一方式锁定, 否则它不会工作)锁定全部文件的一种轻便方法。

flock() 操作的 handle 必须是一个已经打开的文件指针。operation 可以是以下值之一:

  • 要取得共享锁定(读取程序),将 operation 设为 LOCK_SH(PHP 4.0.1 以前的版本设置为 1)。

  • 要取得独占锁定(写入程序),将 operation 设为 LOCK_EX(PHP 4.0.1 以前的版本中设置为 2)。

  • 要释放锁定(无论共享或独占),将 operation 设为 LOCK_UN(PHP 4.0.1 以前的版本中设置为 3)。

  • 如果你不希望 flock() 在锁定时堵塞,则给 operation 加上 LOCK_NB(PHP 4.0.1 以前的版本中设置为 4)。

flock() 允许你执行一个简单的可以在任何平台中使用的读取/写入模型(包括大部分的 Unix 派生版和甚至是 Windows)。如果锁定会堵塞的话(EWOULDBLOCK 错误码情况下),请将可选的第三个参数设置为 TRUE

如果成功则返回 TRUE,失败则返回 FALSE

例子 1. flock() 例子

<?php

$fp
= fopen("/tmp/lock.txt", "w+");

if (
flock($fp, LOCK_EX)) { // 进行排它型锁定
  
fwrite($fp, "Write something here\n");
  
flock($fp, LOCK_UN); // 释放锁定
} else {
   echo
"Couldn't lock the file !";
}

fclose($fp);

?>

注: 由于 flock() 需要一个文件指针, 因此你可能需要一个锁定文件来保护到你打算通过写模式打开来截断的文件的访问(在 fopen() 函数中加入 "w" 或 "w+")。

警告

flock() 不能在 NFS 以及其他的一些网络文件系统中正常工作。详细资料请检查你的操作系统文档。

在部分操作系统中,flock() 以处理级执行。当用一个多线程服务器 API(比如 ISAPI)时,您可能不可以依靠 flock() 来保护文件,因为在同一服务器内运行在其它线程的 PHP 脚本可以对该文件进行处理。

flock() 不支持旧的文件系统,如 FAT 以及它的派生系统。因此,它在这种情况下经常会返回一个 FALSE 值(尤其是指 Windows 98 的用户)。




add a note add a note User Contributed Notes
flock
sbsaylors at yahoo dot com
23-Jan-2002 06:39
Well I needed some kind of "lock" in windows, so I just created a lock.file in that directory.  So if anything wants to 'write' to that file (or append, whatever) it checks to see if a lock.file (or whatever name you want to use) is there and if the date of the file is old.  If its old (1 hour) then it deletes it and goes ahead.  If its not old then it waits a random time.  When its finised it deletes the file.

Seems to work alright but I havent tested anything and its only used for maybe a 100 hits a day but... :)

<filetypefnmatch>
 Last updated: Fri, 22 Jun 2007
view source | feedback | send page | sitemap | aboutus   
Copyright ® 2002-2003 PHPE.NET. All rights reserved
Last updated:2002-11-22