phpzend-certification

Using flock() to lock a stream is only assured to work under what circumstances?


This is a question from PHP zend exam,

Using flock() to lock a stream is only assured to work under what circumstances?


Solution

  • A stream has this set of operationswrite, read, close, flush (mandatory, even if they are no ops) and seek, cast, stat, set_option (optional). When you request a file lock, the set_option operation is called.

    Just from here, you can see that being bi-directional or read-only has nothing to do with this. One could implement an arbitrary wrapper, make the writes and reads have some effect and yet not implement set_option, because it's optional. Likewise, one could implement a no-op write operation and yet handle file locks in my set_option implementation. Running in a Linux environment is also irrelevant, since what matters is what the stream supports.

    (NOTE: I'm not sure what "running in a Linux environment local filesystem" means. I admitted it means "running PHP from the local filesystem in a Linux environment" as opposed to e.g. "running PHP from an AFS filesystem in a Linux environment". It if means "accessing a stream that backs the local filesyste in a Linux environment", this is probably the correct answer, given the manual warning described below).

    The remaining questions involve the STDIO streams. Now, when checking if a stream supports blocking with stream_supports_lock, PHP doesn't actually try a flock, it passes the set_option operation a special value that queries "does this stream support file locking"? The STDIO stream operation always responds it does, so it would appear that all the two remaining answers are correct.

    However, the fact the set_option operation claims it supports file locking doesn't make it true. When you actually try to acquire the lock, it may fail. So when is it guaranteed to work? Surely not Windows shares, since these can be backed by almost anything. We're left with "on the local filesystem". So the answer is, by elimination

    When accessing the stream of the local filesystem

    Note, however, the (admittedly outdated) warning in the manual:

    flock() is not supported on antiquated filesystems like FAT and its derivates and will therefore always return FALSE under this [sic] environments (this is especially true for Windows 98 users).