3

It appears that when php uses flock() to acquire an exclusive lock to a file, and then uses pcntl_fork to split into two processes, both processes have the same exclusive lock - that is to say, further calls to flock($fd, LOCK_EX) on that file handle return true.

But, the point of using flock is to prevent two processes from writing to the same file at the same time. So how does PHP handle this case? Does it allow the two processes, which somehow both have exclusive locks, to conflict? Is there any way (without creating a new file handler) for one processes to detect whether the other process has released the lock?

This is mainly academic curiosity. I know this could be handled by making a new file handler, or as a last resort using IPC to notify the other process, but I wonder if there is any way built in to the flock system to detect duplication of the lock?

1 Answer 1

1

flock operates on the file handle level (in PHP terms, on the file handle resource returned by fopen level) so that when you fork both processes will have the lock because each one has a copy of the same resource.

The point of flock is to prevent simultaneous access, which it does as long as you don't share the file handle with another process. Since sharing is a voluntary operation that's not a practical problem; if you do share, you need to make additional arrangements so that lock exclusivity is maintained.

At the academic level, while it is possible for the kernel to detect the lock duplication after you fork (after all, it knows you have an open file descriptor with which a lock entry is associated), the implementation makes it impossible to do something about it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.