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
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
:
[pid 7246] open("/var/www/file.json", O_RDONLY|O_CLOEXEC) = 11
[pid 7246] fcntl(11, F_GETFD) = 0x1 (flags FD_CLOEXEC)
[pid 7246] mmap(NULL, 20, PROT_READ, MAP_SHARED, 11, 0) = 0x7f53f93da000
[pid 7246] munmap(0x7f53f93da000, 20) = 0
[pid 7246] writev(10, [{"HTTP/1.1 200 OK\r\nDate: Thu, 26 J"}, ...) = 365
[pid 7246] close(11) = 0
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 rename
to overwrite the file.
That way, if the open
has succeeded, apache will continue serving the old file. If the rename
finishes before the open
, 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 fsync in the application that writes the JSON file before closing it.