PHP/File Directory/flock

Материал из Web эксперт
Перейти к: навигация, поиск

If file lock is not available, flock( ) will return immediately with false rather than wait for a lock to become available.

 
<?
    $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";
    }
?>



Locking Files with flock( )

 
<?
    $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";
    }
?>



The file locking mechanism in PHP makes processes queue up for their locks by default

 
<?
    $fp = fopen("foo.txt", "w");
    if (flock($fp, LOCK_EX)) {
            print "Got lock!\n";
            sleep(10);
            flock($fp, LOCK_UN);
    }
?>



Using advisory file locking

 
<?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);
?>