note 99418 deleted from function.flock by mazzanet
| From: | mazzanet@php.net | Date: | Tue, 17 Aug 2010 01:22:28 +0000 |
| Subject: | note 99418 deleted from function.flock by mazzanet | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-171746@lists.php.net to get a copy of this message | ||
Note Submitter: Martin Viktora
----
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);
}
?>