How do I retry PHP flock () for a certain period of time?

I need to open a log file for writing. The problem is that a lot can do this at the same time, and I don't want conflicts. Each record will be a single line, usually around 150 bytes (and always less than 1K), and getting things in chronological order is strictly not required.

I think I want to try flock(), and if it doesn't work, keep trying for a few seconds. If the lock cannot be set after several attempts, release it.

$fh=fopen($logfile, "a");

if (flock($fh, LOCK_EX|LOCK_NB)) {
  $locked=TRUE;
} else {
  $locked=FALSE;
  // Retry lock every 0.1 seconds for 3 seconds...
  $x=0; while($x++ < 30) {
    usleep(100000);
    if (flock($fh, LOCK_EX|LOCK_NB)) {
      $locked=TRUE;
      break;
    }
  }
}

if ($locked) {
  if (fwrite($fh, strftime("[%Y-%m-%d %T] ") . $logdata . "\n")) {
    print "Success.\n";
  } else {
    print "Fail.\n";
  }
  flock($fh, LOCK_UN)
} else {
  print "Lock failed.\n";
}

, . -, - (do...while ..), , PHP? -, PHP? (, , .)

, , syslog(), PHP-, , , (.. /etc/syslog.conf) .

UPDATE: |LOCK_NB , randy .

+5
1

PHP ( Linux!) ( ). :

$fh=fopen($logfile, "a");
if (fwrite($fh, strftime("[%Y-%m-%d %T] ") . $logdata . "\n")) {
    print "Success.\n";
  } else {
    print "Fail.\n";
  }
fclose($fh);

( ) , fopen " a" seek . syslog, , .

, ( ) "" , ( ) .

ADD

apache -: ab, concurrency, , 1000000 , 10to1000.

ADD -

, .

http://php.net/manual/en/function.fwrite.php

fopen() ed , fwrite() s ( , , ). , () fwrite(); .

, ( 4k):

dumpe2fs/dev/sd_your_disk_partition | less -i

"" , "" ( "D" "ps ax" ), PHP , .: * stream_set_blocking *. , .

fwrite ( ) / . IMHO flock .

( ), fwrite , : DB

  • PHP C!
  • full workflow control
  • hi concurrency level
+4
source

All Articles