Jump to content

Avoiding race conditions when opening a file for writing


johnmerlino1

Recommended Posts

I have the following code:

$fp = fopen(“path_to_file”, ‘a’);
flock($fp, LOCK_EX);
fwrite($fp, $string);
flock($fp, LOCK_UN);  
fclose($fp);

If I try to lock the file in two different places at the same time, this will cause a race condition. How can I prevent this? I know in Java, for example, it has a concurrent library which contains reentrant lock, which basically tries to get the lock and if can't waits. What can I do in PHP?

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.