[PHP 7 on Linux]
I'm trying to create a shared configuration file between several asynchronously running PHP scripts.
One script is the "Writer". It will know when new configuration data is available, and is responsible for writing this configuration to the shared config file. No other script will have permission to write to the file. The configuration comprises a JSON string, and should be written in a single fwrite() or file_put_contents().
The data is so small it seems overkill to introduce a database engine or other overly complex mechanism of sharing.
All the other scripts ("Readers") need to be able to open the file at any time and read the contents with the assurance that the contents are complete (not in the process of being written).
The problem with flock() is that if any Reader opens the file and uses LOCK_SH, then the Writer cannot get a LOCK_EX on the file, and will block. Since the Readers open the file at random times, there may be overlap and may never be a time when all Readers release the file, so it's possible the Writer will wait indefinitely without getting an exclusive lock on the file.
The Writer must be able to update the configuration any time a new configuration is applicable, but if any Readers try to open the configuration during the update (or are in the process of reading the existing file), they should still see the previous complete file and not a blank or partially written file.
Would it be best to simply write the updated config to a temporary file, then use rename() to replace the existing file? (rename() appears to be an atomic operation when performed within a file system.)