note 112782 added to function.getmypid
| From: | RaduCristescu | Date: | Mon, 22 Jul 2013 18:44:37 +0000 |
| Subject: | note 112782 added to function.getmypid | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-195717@lists.php.net to get a copy of this message | ||
The lock-file mechanism in Kevin Trass's note is incorrect because it is subject to race
conditions.
For locks you need an atomic way of verifying if a lock file exists and creating it if it
doesn't exist. Between file_exists and file_put_contents, another process could be faster than
us to write the lock.
The only filesystem operation that matches the above requirements that I know of is symlink().
Thus, if you need a lock-file mechanism, here's the code. This won't work on a system
without /proc (so there go Windows, BSD, OS X, and possibly others), but it can be adapted to work
around that deficiency (say, by linking to your pid file like in my script, then operating through
the symlink like in Kevin's solution).
#!/usr/bin/php
<?php
define('LOCK_FILE', "/var/run/" . basename($argv[0], ".php") .
".lock");
if (!tryLock())
die("Already running.\n");
# remove the lock on exit (Control+C doesn't count as 'exit'?)
register_shutdown_function('unlink', LOCK_FILE);
# The rest of your script goes here....
echo "Hello world!\n";
sleep(30);
exit(0);
function tryLock()
{
# If lock file exists, check if stale. If exists and is not stale, return TRUE
# Else, create lock file and return FALSE.
if (@symlink("/proc/" . getmypid(), LOCK_FILE) !== FALSE) # the @ in front of
'symlink' is to suppress the NOTICE you get if the LOCK_FILE exists
return true;
# link already exists
# check if it's stale
if (is_link(LOCK_FILE) && !is_dir(LOCK_FILE))
{
unlink(LOCK_FILE);
# try to lock again
return tryLock();
}
return false;
}
?>
----
Server IP: 69.147.83.199
Probable Submitter: 81.137.34.33
----
Manual Page -- http://php.net/manual/en/function.getmypid.php
Edit -- https://master.php.net/note/edit/112782
Del: integrated -- https://master.php.net/note/delete/112782/integrated
Del: useless -- https://master.php.net/note/delete/112782/useless
Del: bad code -- https://master.php.net/note/delete/112782/bad+code
Del: spam -- https://master.php.net/note/delete/112782/spam
Del: non-english -- https://master.php.net/note/delete/112782/non-english
Del: in docs -- https://master.php.net/note/delete/112782/in+docs
Del: other reasons-- https://master.php.net/note/delete/112782
Reject -- https://master.php.net/note/reject/112782
Search -- https://master.php.net/manage/user-notes.php