Are there any Apache read-lock files before serving them?

I have a mobile application that reads a JSON file that is stored on an Apache server. The content of this JSON file is restored (using a PHP script) if something changes using the graphical user interface.

I fear that trying to overwrite a JSON file in the middle of its Apache maintenance might cause problems.

Does Apache get a read lock before file submission? If not, what happens if I try to record it at the same time when it will be serviced?

+8
json php locking apache
source share
2 answers

Not. On POSIX-compatible systems, all locks are advisable anyway, so even if apache gets a read lock, another process may 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 may happen that your JSON file is only partially written. To avoid this problem, write your JSON file to a temporary file in the same file system and use atomic rename to overwrite the file.

That way, if open succeeds, apache will continue to serve the old file. If rename ends before open , apache will receive a new completed file.

If you are worried about the sequence (in the event of a power failure or so), you can also call fsync in an application that writes JSON before closing the file.

+9
source share

You are thinking of the wrong paradigm for * nix platforms. You want the Atom file to be written to the JSON file in your script. You do this by writing the file to a unique temporary file name in the destination directory, and then using rename() to move this file over the old one. The file move operation is atomic. Asynchronous processes will either open the old JSON file, or a new one, but not a hybrid.

There are various ways to create a temporary file name. See the PHP documentation user comments on tempnam() . My system generates a unique request identifier, so I just use $_SERVER["UNIQUE_ID"] as the base.

+1
source share

All Articles