Is flock necessary?

From: Date: Thu, 07 Mar 2002 04:54:40 +0000
Subject: Is flock necessary?
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-87579@lists.php.net to get a copy of this message
Group: Is flock even necessary? Allan: You look like you have Perled. It was necessary for Perl. Have you thought of MySQL instead? Alan McFarlane wrote: > 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) -- John Taylor-Johnston ----------------------------------------------------------------------------- ' ' ' Collège de Sherbrooke: ô¿ô http://www.collegesherbrooke.qc.ca/languesmodernes/ - Université de Sherbrooke: http://compcanlit.ca/ 819-569-2064

« previous php.general (#87579) next »