note 79915 deleted from function.flock by danbrown
| From: | danbrown@php.net | Date: | Mon, 18 May 2009 00:34:40 +0000 |
| Subject: | note 79915 deleted from function.flock by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-155390@lists.php.net to get a copy of this message | ||
Note Submitter: jpriebe at cbcnewmedia dot com
----
mallory.dessaintes' message leads to another challenge with flock() -- if the file handle goes
out of scope, the locking mechanism doesn't work.
Imagine you have a long-running command-line PHP script. You schedule it to run via cron every
minute, but you only want one copy at a time to run.
You might implement a function like this:
<?php
function get_lock ()
{
$fp = @fopen ('/tmp/myscript.lock', 'w+');
if (!$fp)
{
return false;
}
if (flock ($fp, LOCK_EX + LOCK_NB))
{
return true;
}
return false;
}
?>
But when the function returns, the $fp variable goes out of scope, and the lock is broken. You need
to make your file handle variable global like this:
<?php
function get_lock ()
{
global $g_lock_fp;
$g_lock_fp = @fopen ('/tmp/myscript.lock', 'w+');
if (!$g_lock_fp)
{
return false;
}
if (flock ($g_lock_fp, LOCK_EX + LOCK_NB))
{
return true;
}
return false;
}
?>