note 111831 deleted from function.fopen by cmb

From: Date: Fri, 09 Sep 2016 22:35:28 +0000
Subject: note 111831 deleted from function.fopen by cmb
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-206551@lists.php.net to get a copy of this message
Note Submitter: simon dot riget at gmail dot com ---- The following is an example of file locking used in a function to share an array between processes. In this example the function reads the array, possibly remove stuff like spend semaphores and insert new stuff to share. The file gets locked for writing thus making sure that two processes doesn't inadvertently delete each others data. The function can be called multiple times during a script, which becomes increasingly important if you write HTML5 Server Sent Events and websockets apps, since the script dose not end when the page are loaded. (there are other issues with that like garbage collection and memory leaks) Using the “c” mode of fopen, removes the (remote) change of a race condition to the file lock. Be aware that the function filesize() is not working correctly when files are in cash memory. You could flush the cash or in this case, since the file size of IPC are neglectable, just give a very large number as length parameter to fread. <?php function ipc($new_record=""){ $update=false; // Open file with locking $handle=fopen("example.dat","c+"); // Lock the file for writing flock($handle,LOCK_EX); // Get file size. // you can either fluch the file cash to get an acurate number // clearstatcache(); // Or use a large number // Load event file into array $contents=fread($handle,10000000); $ipc_array=json_decode($contents,true); // Clean out old stuff if(is_array($ipc_array)){ $timeout=time()-60; foreach($ipc_array as $key=>$record){ // eg remove spend semaphores or timed out messages if( $record['time'] < $timeout ){ unset($ipc_array[$key]); $update=true; } } } // Add new message if(is_array($new_record)){ $new_record['time']=time(); $ipc_array[]=$new_record; $update=true; } // Write file and end if($update){ // Overwrite the old data ftruncate($handle,0); rewind($handle); // Write the new array to file fwrite($handle,json_encode($ipc_array,JSON_NUMERIC_CHECK)); } // Unlock the file - you have to do it! it doesn't happen on fclose flock($handle,LOCK_UN); // Close the file fclose($handle); return $ipc_array; } // Read messages $ipc=ipc(); // Show messages foreach( $ipc as $record) echo $record['message'] ."<br>\n"; // Send a message $message["message"]="hello world."; $message["foo"]="bar"; $ipc=ipc($message); ?>

« previous php.notes (#206551) next »