PHP flock() 函数

定义和用法

flock() 函数锁定或释放文件。

若成功,则返回 true。若失败,则返回 false。

语法

flock(file,lock,block)
参数 描述
file 必需。规定要锁定或释放的已打开的文件。
lock 必需。规定要使用哪种锁定类型。
block 可选。若设置为 1 或 true,则当进行锁定时阻挡其他进程。

Description

The operation of file Must be an already opened file pointer.

lock The parameter can be one of the following values:

  • To obtain a shared lock (reading program), set lock to LOCK_SH (set to 1 in versions before PHP 4.0.1).
  • To obtain an exclusive lock (writing program), set lock to LOCK_EX (set to 2 in versions before PHP 4.0.1).
  • To release the lock (whether shared or exclusive), set lock to LOCK_UN (set to 3 in versions before PHP 4.0.1).
  • If you do not want flock() to block during locking, then set lock Add LOCK_NB (set to 4 in versions before PHP 4.0.1).

Tips and Comments

Tip:Can be done by fclose() To release the locking operation, the code will also automatically call when the code execution is completed.

Comment:Since flock() requires a file pointer, it may be necessary to use a special locking file to protect access to files intended to be opened in write mode (add "w" or "w+" in the fopen() function).

Example

<?php
$file = fopen("test.txt","w+");
// exclusive lock
if (flock($file,LOCK_EX))
  {
  fwrite($file,"Write something");
  // release lock
  flock($file,LOCK_UN);
  }
else
  {
  echo "Error locking file!";
  }
fclose($file);
?>