Answer the question
In order to leave comments, you need to log in
Question about flock in php?
Hello!
There were questions about writing data to a file (s) using locks (flock).
Interested in its reliability.
Let's say if two processes want to lock a file at the same time, what will happen? Will there be a queue or will they both go to write to him?
If it is unreliable, then tell me a more reliable option.
Answer the question
In order to leave comments, you need to log in
flock() has no guaranteed behavior in general, on *nix it's better to use semaphores in my opinion .
If your software will be installed on a third-party environment, then you should definitely not rely on flock.
If you are writing something for yourself, and you know for sure that, for example, the environment will not go beyond linux / freebsd + apache / nginx, you can safely use it.
If two processes want to lock a file, the second process will wait for the lock to be released. When the first one releases the lock, the flock() execution in the second process will end and the process will continue executing the code.
A more reliable option for all occasions is to organize lock yourself through files / database / memcache, etc.
That’s because it’s not very clear and I don’t want to use it :) And the point there, in my opinion, is that flock can work somewhere at the process level, and not at the kernel / fs level, that is, it will destroy several threads in one process, but the fact that another process also locked the file and does not recognize it. There will be no deadlock, but two processes will write to the file.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question