Test if file is locked

后端 未结 2 509
自闭症患者
自闭症患者 2020-12-09 12:50

In PHP, how can I test if a file has already been locked with flock? For example, if another running script has called the following:

$fp = fopen(\'thefile.t         


        
相关标签:
2条回答
  • 2020-12-09 13:14

    Check it like this:

    if (!flock($file, LOCK_EX)) {
        throw new Exception(sprintf('File %s is locked', $file));
    }
    
    fwrite($file, $write_contents);
    
    0 讨论(0)
  • 2020-12-09 13:17
    if (!flock($fp, LOCK_EX|LOCK_NB, $wouldblock)) {
        if ($wouldblock) {
            // another process holds the lock
        }
        else {
            // couldn't lock for another reason, e.g. no such file
        }
    }
    else {
        // lock obtained
    }
    

    As described in the docs, use LOCK_NB to make a non-blocking attempt to obtain the lock, and on failure check the $wouldblock argument to see if something else holds the lock.

    0 讨论(0)
提交回复
热议问题