note 99418 added to function.flock
| From: | MartinViktora at osu1 dot php dot net | Date: | Mon, 16 Aug 2010 12:06:38 +0000 |
| Subject: | note 99418 added to function.flock | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-171732@lists.php.net to get a copy of this message | ||
The lock on a file will exists only as long as the file resource variable exists. It took me an hour
to realize that PHP does some garbage collection (unlike C) so when you open the lock file inside a
function call and store the lock file resource in a local variable, then the lock will be
automatically released upon function return as PHP will automatically closes the lock file resource:
<?php
// Won't work: lock is lost upon function return
function acquireLock($lockFilePath)
{
$fp = fopen($lockFilePath, "w+");
if($fp === false)
die("Lock file cannot be opened");
flock($fp, LOCK_EX);
// Since $fp is not stored in any variable outside of this function,
// when the function returns, $fp is automatically closed by PHP
// and therefore the lock is released.
}
// Correct way: make $fp a global variable, which will guarantee it will exist
// for the entire script execution time
function acquireLock($lockFilePath)
{
global $fp;
$fp = fopen($lockFilePath, "w+");
if($fp === false)
die("Lock file cannot be opened");
flock($fp, LOCK_EX);
}
?>
----
Server IP: 69.147.83.197
Probable Submitter: 81.201.60.140
----
Manual Page -- http://www.php.net/manual/en/function.flock.php
Edit -- https://master.php.net/note/edit/99418
Del: integrated -- https://master.php.net/note/delete/99418/integrated
Del: useless -- https://master.php.net/note/delete/99418/useless
Del: bad code -- https://master.php.net/note/delete/99418/bad+code
Del: spam -- https://master.php.net/note/delete/99418/spam
Del: non-english -- https://master.php.net/note/delete/99418/non-english
Del: in docs -- https://master.php.net/note/delete/99418/in+docs
Del: other reasons-- https://master.php.net/note/delete/99418
Reject -- https://master.php.net/note/reject/99418
Search -- https://master.php.net/manage/user-notes.php