Press "Enter" to skip to content

PHP对文件的一些操作

flock(resource $stream, int $operation, int &$would_block = null): bool

锁定文件

//参数说明:

stream

文件系统指针,是典型地由 fopen() 创建的 resource(资源)。operation

operation 可以是以下值之一:

  • LOCK_SH取得共享锁定(读取的程序)。
  • LOCK_EX 取得独占锁定(写入的程序。
  • LOCK_UN 释放锁定(无论共享或独占)。

would_block

如果锁将堵塞(EWOULDBLOCK 错误码情况下),第三个可选参数会设置为 1。

写文件的一些流程

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

if (flock($fp, LOCK_EX)) {  // 进行排它型锁定
    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);
if(!($cachefile && $fp && flock($fp, LOCK_EX) && ftruncate($fp, 0) && fwrite($fp, $template) && fflush($fp) && flock($fp, LOCK_UN) && fclose($fp))) {
return $template;
}

发表评论