I have an mobile app that reads a JSON file that is stored on an Apache server. The contents of that JSON file are regenerated (using a PHP script) if something is changed via a GUI.
I am worried that trying to overwrite the JSON file in the middle of it being served by Apache might cause problems.
Does Apache obtain a read lock before serving files? If not, what will happen if I try to write it at the same time it is being served?
No. On POSIX-compatible systems, all locks are advisory anyways, so even if apache would get a read lock, the other process could just write the file.
You can determine that with
strace:Therefore, it can happen that your JSON file is only partially written. To avoid this problem, write your JSON file to a temporary file on the same filesystem, and use the atomic
renameto overwrite the file.That way, if the
openhas succeeded, apache will continue serving the old file. If therenamefinishes before theopen, apache will get the new, completed file.If you worry about consistency (in the case of a power failure or so), you may also want to call
fsyncin the application that writes the JSON file before closing it.