检查文件是否被并发进程锁定

问题描述 投票:1回答:3

我有一个使用file_put_contents()写入文件的进程:

file_put_contents ( $file, $data, LOCK_EX );

我添加了LOCK_EX参数以防止并发进程写入同一个文件,并防止在仍然被写入时尝试读取它。

由于并发性,我在测试这个问题时遇到了困难,而且我不确定如何处理这个问题。到目前为止我有这个:

if (file_exists($file)) {
    $fp = fopen($file, 'r+');
    if (!flock($fp, LOCK_EX|LOCK_NB, $wouldblock)) {
        if ($wouldblock) {
            // how can I wait until the file is unlocked?
        } else {
            // what other reasons could there be for not being able to lock?
        }
    }
    // does calling fclose automatically close all locks even is a flock was not obtained above?
    fclose($file);
}

问题是:

  1. 有没有办法等到文件不再被锁定,同时保持选项给这个时间限制?
  2. 当有另一个锁定文件的进程时,fclose()会自动解锁所有锁吗?
php fopen fclose flock
3个回答
1
投票

我经常使用一个小类...这是安全和快速的,基本上你只有在你获得文件的独占锁定时才能写,否则你应该等到被锁定...

lock_file.php

<?php
  /*
  Reference Material
  http://en.wikipedia.org/wiki/ACID
  */
  class Exclusive_Lock {
    /* Private variables */
    public $filename; // The file to be locked
    public $timeout = 30; // The timeout value of the lock
    public $permission = 0755; // The permission value of the locked file
    /* Constructor */
    public function __construct($filename, $timeout = 1, $permission = null, $override = false) {
      // Append '.lck' extension to filename for the locking mechanism
      $this->filename = $filename . '.lck';
      // Timeout should be some factor greater than the maximum script execution time
      $temp = @get_cfg_var('max_execution_time');
      if ($temp === false || $override === true) {
        if ($timeout >= 1) $this->timeout = $timeout;
        set_time_limit($this->timeout);
      } else {
        if ($timeout < 1) $this->timeout = $temp;
        else $this->timeout = $timeout * $temp;
      }
      // Should some other permission value be necessary
      if (isset($permission)) $this->permission = $permission;
    }
    /* Methods */
    public function acquireLock() {
      // Create the locked file, the 'x' parameter is used to detect a preexisting lock
      $fp = @fopen($this->filename, 'x');
      // If an error occurs fail lock
      if ($fp === false) return false;
      // If the permission set is unsuccessful fail lock
      if (!@chmod($this->filename, $this->permission)) return false;
      // If unable to write the timeout value fail lock
      if (false === @fwrite($fp, time() + intval($this->timeout))) return false;
      // If lock is successfully closed validate lock
      return fclose($fp);
    }
    public function releaseLock() {
      // Delete the file with the extension '.lck'
      return @unlink($this->filename);
    }
    public function timeLock() {
      // Retrieve the contents of the lock file
      $timeout = @file_get_contents($this->filename);
      // If no contents retrieved return error
      if ($timeout === false) return false;
      // Return the timeout value
      return intval($timeout);
    }
  }
?>

简单使用如下:

  include("lock_file.php");
  $file = new Exclusive_Lock("my_file.dat", 2);
  if ($file->acquireLock()) {
    $data = fopen("my_file.dat", "w+");
    $read = "READ: YES";
    fwrite($data, $read);
    fclose($data);
    $file->releaseLock();
    chmod("my_file.dat", 0755);
    unset($data);
    unset($read);
  }

如果你想添加更复杂的级别,你可以使用另一个技巧...使用while (1)初始化一个无限循环,只有在获得独占锁时才会中断,不建议因为可以阻止你的服务器一个未定义的时间......

  include("lock_file.php");
  $file = new Exclusive_Lock("my_file.dat", 2);
  while (1) {
    if ($file->acquireLock()) {
      $data = fopen("my_file.dat", "w+");
      $read = "READ: YES";
      fwrite($data, $read);
      fclose($data);
      $file->releaseLock();
      chmod("my_file.dat", 0755);
      unset($data);
      unset($read);
      break;
    }
  }

file_put_contents()非常快,直接写入文件,但正如你所说有一个限制...竞争条件存在,即使你试图使用LOCK_EX可能会发生。我认为php类更灵活,更实用......

看到这个处理类似问题的线程:php flock behaviour when file is locked by one process


0
投票

第一个问题在这里回答How to detect the finish with file_put_contents() in php?和beacuse PHP是单线程的,唯一的解决方案是使用PTHREADS使用核心PHP的扩展,一个关于它的简单文章是https://www.mullie.eu/parallel-processing-multi-tasking-php/

第二个问题在这里回答Will flock'ed file be unlocked when the process die unexpectedly?

fclose()将仅解锁使用fopen()或fsockopen()打开的有效句柄,因此如果句柄仍然有效,则是它将关闭文件并释放锁定。


0
投票

我编写了一个使用sleep()的小测试,以便我可以通过简单的AJAX调用来模拟并发读/写过程。这似乎回答了这两个问题:

  1. 当文件被锁定时,一个接近估计写入持续时间的睡眠和随后的锁定检查允许等待。这甚至可以放入具有间隔的while循环。
  2. fclose()确实没有从已经运行的进程中删除锁定,如某些答案中所确认的那样。

Windows上的PHP5.5及更低版本根据文档不支持$wouldblock参数,我能够在Windows + PHP5.3上测试这个并得出结论,我的测试中的file_is_locked()仍然在这种情况下工作:flock()仍然会返回false没有$wouldblock参数但它仍然会在我的else检查中被捕获。

if (isset($_POST['action'])) {
    $file = 'file.txt';
    $fp = fopen($file, 'r+');
    if ($wouldblock = file_is_locked($fp)) {
        // wait and then try again;
        sleep(5);
        $wouldblock = file_is_locked($fp);
    }
    switch ($_POST['action']) {
        case 'write':
            if ($wouldblock) {
                echo 'already writing';
            } else {
                flock($fp, LOCK_EX);
                fwrite($fp, 'yadayada');
                sleep(5);
                echo 'done writing';
            }
            break;
        case 'read':
            if ($wouldblock) {
                echo 'cant read, already writing';
            } else {
                echo fread($fp, filesize($file));
            }
            break;
    }

    fclose($fp);
    die();
}

function file_is_locked( $fp ) {
    if (!flock($fp, LOCK_EX|LOCK_NB, $wouldblock)) {
        if ($wouldblock) {
            return 'locked'; // file is locked
        } else {
            return 'no idea'; // can't lock for whatever reason (for example being locked in Windows + PHP5.3)
        }
    } else {
        return false;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.