PHP/File Directory/flock
Содержание
If file lock is not available, flock( ) will return immediately with false rather than wait for a lock to become available.
<source lang="html4strict">
<?
$fp = fopen("foo.txt", "w"); if (flock($fp, LOCK_EX | LOCK_NB)) { echo "Got lock!\n"; sleep(10); flock($fp, LOCK_UN); } else { print "Could not get lock!\n"; }
?>
</source>
Locking Files with flock( )
<source lang="html4strict">
<?
$fp = fopen( $filename,"w"); // open it for WRITING ("w") if (flock($fp, LOCK_EX)) { // do your file writes here flock($fp, LOCK_UN); // unlock the file } else { // flock( ) returned false, no lock obtained print "Could not lock $filename!\n"; }
?>
</source>
The file locking mechanism in PHP makes processes queue up for their locks by default
<source lang="html4strict">
<?
$fp = fopen("foo.txt", "w"); if (flock($fp, LOCK_EX)) { print "Got lock!\n"; sleep(10); flock($fp, LOCK_UN); }
?>
</source>
Using advisory file locking
<source lang="html4strict">
<?php $fh = fopen("guestbook.txt","a") or die($php_errormsg); flock($fh,LOCK_EX) or die($php_errormsg); fwrite($fh,$_POST["guestbook_entry"]) or die($php_errormsg); fflush($fh) or die($php_errormsg); flock($fh,LOCK_UN) or die($php_errormsg); fclose($fh) or die($php_errormsg); ?>
</source>