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?
File locking is a mechanism that restricts access to a computer file, or to a region of a file, by allowing only one user or process to modify or delete it at a specific time and to prevent reading of the file while it's being modified or deleted.
In Java, a file lock can be obtained using FileChannel , which provides two methods — lock() and tryLock() — for this purpose. The lock() method acquires an exclusive lock on entire file, whereas the lock(long position, long size, boolean shared) method can be used to acquire a lock on the given region of a ile.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With