Use of flock()

From: Date: Thu, 07 Mar 2002 03:20:16 +0000
Subject: Use of flock()
Groups: php.general 
Request: Send a blank email to php-general+get-87567@lists.php.net to get a copy of this message
I've just written a couple of simple routines which read an write small text files to the server: function readData( $filename, &$data ) { if (!$fd = @fopen($filename, "r")) { return false; } flock($fd, LOCK_SH); $data = fread($fd, filesize($filename)); fclose($fd); return true; } function writeData( $filename, $data ) { if (!$fd = @fopen($filename, "w")) { return false; } flock($fd, LOCK_EX); fwrite($fd, $data); fclose($fd); return true; } Now, the question is... How much time elapses between the fopen() statement and the flock() statements? Looking at the code, it would appear that two separate threads may call writeData() almost simultaneously giving the following execution: assume $filename = "sample.txt"; Thread #1 - $fd = fopen($filename, "w"); // succeeds Thread #2 - $fd = fopen($filename, "w"); // succeeds (I think) Thread #1 - flock($fd, LOCK_EX); // Does this succeed or fail? Thread #2 - flock($fd, LOCK_EX); // fails (I think)

« previous php.general (#87567) next »