Re: Behavior of the sleep function?

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Jeffry Killen wrote:

> I am experimenting with flock to find out how it works.
> 
> I set up a page with a form that uses javascript ajax async 'get'
> to query the server.
> 
> The reason for using ajax is that the page will not reload so
> I can keep a count of the queries issued and simulate two different
> users trying to edit the file.
> 
> I am assuming that the first query (which calls flock and invokes the
> sleep function)
> would block the second query.
> 
> But the second query succeeds and the the first query returns after 10
> seconds
> 
> Here is the code:
> 
> <?php
> 
> $_jsTest = '';
> $_error = '';
> if(!is_file('lab6_target.txt'))
>   {
>    if(is_writeable('./'))
>      {
>       $_fw = fopen('lab6_target.txt', 'w');
>       fwrite($_fw, "some bs text for the sake of testing this turkey.");
>       fclose($_fw);
>      }
>   }
> if($_GET)
>   {
>    if($_GET['tstNo'] == '1')
>      {
>       $_jsTest = $_GET['tst1'];
>       $_fw = fopen('lab6_target.txt', 'a');
>       flock($_fw, LOCK_EX); // LOCK_SH, LOCK_EX, LOCK_UN
>       $_error = "starting 10 second sleep";
>       header('Content-Type: text/plain');
>       print $_error;
>       sleep(10);
>       fwrite($_fw, $_GET['tst1']);
>       flock($_fw, LOCK_UN);
>       fclose($_fw);
>       exit;
>      }
>    else if($_GET['tstNo'] == '2')
>      {
>       $_jsTest = $_GET['tst1'];
>       $_fw = fopen('lab6_target.txt', 'a');
>       if(!$_fw)
>         {
>          header('Content-Type: text/plain');
>          print "file not opened for write on second test";
>          exit;
>         }
>       else
>         {
>          fwrite($_fw, $_GET['tst1']);
>          fclose($_fw);
>          header('Content-Type: text/plain');
>          print "success";
>          exit;
>         }
>      }
>   }
> ?>
> 
> Test Result: successstarting 10 second sleep

flock() implements *advisory* file locking, i.e. it works only if *all*
file accesses use flock() to probe for a lock.  So, basically, you have
to call flock($_fw, LOCK_EX) also for $_GET['tstNo'] == '2'.

-- 
Christoph M. Becker


-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php





[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux