PHP:您可以读取具有排他锁的文件吗? [英] PHP: Can you read a file that has an exclusive lock on it?

查看:158
本文介绍了PHP:您可以读取具有排他锁的文件吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我了解,当您通过flock($handle, LOCK_EX)为用户授予文件的排他锁时,您将阻止其他人对该文件进行写入,直到该文件被释放为止.

但是,其他人仍然可以打开共享锁以从文件中读取吗?例如,flock($handle, LOCK_SH).

这是针对平面文件数据库系统的,我希望人们能够在有人写入数据库的情况下仍然查询该数据库,但要阻止多个人一次写入数据库.

解决方案

使用"file_get_contents"读取文件将忽略任何文件锁定.实际上,"file_get_contents"读取到文件的末尾(如果您当时正在写入文件,它将读取它可以获取的内容并返回该内容).

使用"fread"或"fgets"进行文件读取将执行相同的操作,但是您可以首先使用"flock"来确保文件未锁定,但仍有可能出现赛车状况.

您面临的最大问题是,并非所有的linux服务器都支持它,因为"flock"使用的是"advisory" 的系统调用,因此被忽略(通过不锁定任何文件)在某些服务器上.这就是SQLite或MySQL之类的数据库服务器通过提供其自身不依赖于服务器的锁定机制而进入的地方,并且在大多数情况下,在避免竞标条件可能会破坏您的平面文件数据库的情况下,它们也更加聪明. >

As far as I understand when you give a user an exclusive lock to a file via flock($handle, LOCK_EX) you stop others from writing to the file until it is released.

However is it still possible for others to open a shared lock to read from the file? e,g, flock($handle, LOCK_SH).

This is for a flatfile database system and I want people to be able to still query the database if someone is writing to it, but stop multiple people writing to it at once.

解决方案

File reads using "file_get_contents" ignore any file locking. In practice, "file_get_contents" reads up to the end of the file (if you're writing to it at that time, it reads what it can get and returns that).

File reads using "fread" or "fgets" would do the same but you can use "flock" first to make sure the file is not locked, but there's still chance for a racing condition.

The biggest problem you're actually facing is that not all linux servers will support it as "flock" uses system calls that are "advisory" and therefore simply ignored (by not locking any file) on some servers. That's where database servers like SQLite or MySQL come in by providing their own locking mechanisms that don't depend on the server and - most of the time - are smarter too when it comes to avoiding racing conditions that might break your flatfile database.

这篇关于PHP:您可以读取具有排他锁的文件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆