note 79915 added to function.flock

From: Date: Wed, 19 Dec 2007 17:18:19 +0000
Subject: note 79915 added to function.flock
Groups: php.notes 
Request: Send a blank email to php-notes+get-133782@lists.php.net to get a copy of this message
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; } ?> ---- Server IP: 64.71.164.2 Probable Submitter: 64.128.222.130 ---- Manual Page -- http://www.php.net/manual/en/function.flock.php Edit -- https://master.php.net/note/edit/79915 Del: integrated -- https://master.php.net/note/delete/79915/integrated Del: useless -- https://master.php.net/note/delete/79915/useless Del: bad code -- https://master.php.net/note/delete/79915/bad+code Del: spam -- https://master.php.net/note/delete/79915/spam Del: non-english -- https://master.php.net/note/delete/79915/non-english Del: in docs -- https://master.php.net/note/delete/79915/in+docs Del: other reasons-- https://master.php.net/note/delete/79915 Reject -- https://master.php.net/note/reject/79915 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#133782) next »