Check if a file is already locked using flock()? [duplicate]

∥☆過路亽.° 提交于 2019-12-01 04:14:25

I would check to see if I couldn't obtain a lock on the file, like this:

if (!flock($file, LOCK_EX)) {
    throw new Exception(sprintf('Unable to obtain lock on file: %s', $file));
}

fwrite($file, $write_contents);
Ryan Yoosefi

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.

if (!flock($fp, LOCK_EX|LOCK_NB, $wouldblock)) {
    if ($wouldblock) {
        // something already has a lock
    }
    else {
        // couldn't lock for some other reason
    }
}
else {
    // lock obtained
}

Your flock call is the check to see if it's already locked. If it's locked, that if() statement would fail, so you could just throw an else on it with something like:

if (flock($file, LOCK_EX)) {//lock was successful
    fwrite($file,$write_contents);
} else {
    echo "$file is locked.";
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!