note 109175 added to function.flock

From: Date: Tue, 26 Jun 2012 11:21:18 +0000
Subject: note 109175 added to function.flock
Groups: php.notes 
Request: Send a blank email to php-notes+get-188797@lists.php.net to get a copy of this message
Hello, There is couple of reasons why EVERY software developer should avoid its usage if it is possible. My own server was crashed couple of times because of flock (including hours of down time). So you have to think twice before you will decide to use it. After a while I have found the problematic situations. For my surprise it was not just badly written PHP scripts, it was some unclear bugs in FreeBSD. In some case, when more than 20 requests per second try to do exclusive flock on the same file, the scripts stuck ;) and they were using 100% of CPU (only Apache’s reboot or manual kill could stop them). Soon after I have found nice solution (thanks arne at bukkie dot nl for good suggestion). I want to share it with you: <?php // waiting until file will be locked for writing (1000 milliseconds as timeout) if ($fp = fopen($fileName, 'a')) { $startTime = microtime(); do { $canWrite = flock($fp, LOCK_EX); // If lock not obtained sleep for 0 - 100 milliseconds, to avoid collision and CPU load if(!$canWrite) usleep(round(rand(0, 100)*1000)); } while ((!$canWrite)and((microtime()-$startTime) < 1000)); //file was locked so now we can store information if ($canWrite) { fwrite($fp, $dataToSave); } fclose($fp); }?> I have added simple timeout value for flock. Case flock was not obtained within N seconds - writing will be skipped, instead of waiting and causing server’s high CPU load. With best regards Owner of http://listofproxy.net ---- Server IP: 69.147.83.197 Probable Submitter: 112.211.218.71 ---- Manual Page -- http://www.php.net/manual/en/function.flock.php Edit -- https://master.php.net/note/edit/109175 Del: integrated -- https://master.php.net/note/delete/109175/integrated Del: useless -- https://master.php.net/note/delete/109175/useless Del: bad code -- https://master.php.net/note/delete/109175/bad+code Del: spam -- https://master.php.net/note/delete/109175/spam Del: non-english -- https://master.php.net/note/delete/109175/non-english Del: in docs -- https://master.php.net/note/delete/109175/in+docs Del: other reasons-- https://master.php.net/note/delete/109175 Reject -- https://master.php.net/note/reject/109175 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#188797) next »