George Reith
George Reith

Reputation: 13476

PHP: Can you read a file that has an exclusive lock on it?

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.

Upvotes: 1

Views: 1635

Answers (1)

user1093284
user1093284

Reputation:

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.

Upvotes: 1

Related Questions