Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use flock in PHP? [closed]

Tags:

php

In my php code, I want to create a reader/writer code. So there will be a file that the php code wither reads or writes to. There can only be 1 writer, or there can be many readers, but you can write and read at the same time.

How can this be done in PHP? I believe you need to use the flock code?

like image 341
omega Avatar asked Mar 08 '13 23:03

omega


2 Answers

I'm with Danack's comment - the php documentation of flock() contains a very good example:

$fp = fopen("/tmp/lock.txt", "r+");

if (flock($fp, LOCK_EX)) { // exclusive lock will blocking wait until obtained

    fwrite($fp, "Write something here\n");

    // or ...

    execute_code_that_shouldnt_run_twice_at_the_same_time();

    flock($fp, LOCK_UN); // unlock
} else {
    echo "failed to obtain lock";
}

fclose($fp);

Note that flock() in default mode will blocking wait until it can obtain the lock. This is regulary the case if the other process obtains the lock currently.


But don't expect too much from the flock() function. It is using so called advisory locks, which can be ignored by other processes. On Linux for example PHP's flock() is using the kernel function flock(), man 2 flock explains how it works:

flock() places advisory locks only; given suitable permissions on a file, a process is free to ignore the use of flock() and perform I/O on the file.

Meaning flock() will just give an advice to other processes. If they don't care about they can read or even write regardless of the lock ( or type of lock). However the man pages are about Linux other system may handle this differently. (It's not the case actually)

But, however as you are the coder of the processes you can / and should care about the lock using flock() every time you access the file. But you cannot be sure that another process - like a text editor - will not overwrite your file

like image 57
hek2mgl Avatar answered Sep 23 '22 05:09

hek2mgl


If you want to read and write at the same time, well you can't. It's unsafe behaviour. Just use exclusive lock to write, and your readers (using shared lock) will block while waiting to be able to read it. That way they're never able to read from a part-finished file, but will always be able to read eventually.

Oh and don't lock the file for longer than you need to. If you're making prolonged changes (e.g. waiting on network activity), lock it, update, unlock, wait until you get more data, lock it, update, unlock. Or better yet, buffer the data internally and write it in one go.

like image 44
Dave Avatar answered Sep 20 '22 05:09

Dave