note 62084 deleted from function.flock by danbrown

From: Date: Mon, 18 May 2009 00:39:02 +0000
Subject: note 62084 deleted from function.flock by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-155405@lists.php.net to get a copy of this message
Note Submitter: jbr at ya-right dot com ---- On Windows ISAPI testing a file or directory with flock does not return TRUE OR FALSE, it just results in a system hang until the prior flock called has been released. So it is sometimes better to create a fake locking system that gives you complete control of the IO handle so you can exist or move on if the lock is not released at a certain number of tries or time, to get at the file! // PHP 5 example <? $file = './log.txt'; // the file we are writing to $data = "add this\r\n"; // data to add $write_type = 'a'; // append to the file $lock_name = './lock'; // the fake locking file name $lock_tries = 10; // the number of times to try and open the file // usage if ( fake_lock ( $file, $data, $write_type, $lock_name, $lock_tries ) === true ) { echo 'data written to file'; } else { echo 'could not write data to file!'; } function fake_lock ( $fl_file, $fl_data, $fl_write, $fl_name, $fl_try ) { $fl_done = false; $fl_count = 0; $fl_key = md5 ( uniqid ( microtime () ) ); do { $fl_count++; if ( ! file_exists ( $fl_name ) ) { file_put_contents ( $fl_name, $fl_key ); $fl_test = file_get_contents ( $fl_name ); if ( $fl_test == $fl_key ) { $fl_done = true; } } if ( ! $fl_done ) { if ( $fl_count == $fl_try ) { return ( false ); } else { usleep ( 10000 ); } } } while ( ! $fl_done ); $io = fopen ( $fl_file, $fl_write ); fputs ( $io, $fl_data ); fclose ( $io ); unlink ( $fl_name ); return ( true ); } ?>

« previous php.notes (#155405) next »