Does Apache read-lock files before serving them?

后端 未结 2 601
说谎
说谎 2021-01-17 14:49

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

2条回答
  •  伪装坚强ぢ
    2021-01-17 15:45

    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.

提交回复
热议问题