1

What happens if a PHP script wants to:

file_put_contents("testfile", $s, FILE_APPEND | LOCK_EX);

while another script already does the same thing on the same file (with a LOCK_EX too)?

It's unlikely to happen that 2 scripts want to write exactly during the same millisecond (for a < 100 kB file), but let's imagine it happens.

Would the file_put_contents function notice it's locked, wait for say 10ms and then retry, or would the PHP script fail, and the data to be written is lost?

Basj
  • 41,386
  • 99
  • 383
  • 673

1 Answers1

2

Both processes will call flock() to lock the file before they start writing. The first one will get the lock, the second will wait until the file is unlocked. There's no retrying, it's handled automatically by the OS. The documentation doesn't mention a timeout, so I assume there isn't one.

The first process will unlock the file as soon as it finishes writing, then the second process will run.

You generally don't need LOCK_EX if you're using FILE_APPEND. Each call to write() is atomic, and when the file is opened in append mode the filesystem ensures that each process writes at the new end-of-file, not EOF position when the file was opened.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Thank you for your answer. `the second will wait until the file is unlocked`: how long will it wait, under Linux Debian 9 for example? Let's say the file is locked during 10 seconds (unlikely to happen), will the other file wait 10 seconds? – Basj Oct 17 '19 at 15:48
  • The documentation doesn't mention any timeout, so I assume it will wait as long as it takes. – Barmar Oct 17 '19 at 16:20