Test if file is locked

淺唱寂寞╮ 提交于 2019-11-27 02:30:02

问题


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.txt', 'w');
flock($fp, LOCK_EX);

回答1:


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.




回答2:


Check it like this:

if (!flock($file, LOCK_EX)) {
    throw new Exception(sprintf('File %s is locked', $file));
}

fwrite($file, $write_contents);


来源:https://stackoverflow.com/questions/20771824/test-if-file-is-locked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!