@@ -70,6 +70,7 @@ private function getFilePath($keyword, $skip = false) {
7070
7171 function driver_set ($ keyword , $ value = "" , $ time = 300 , $ option = array () ) {
7272 $ file_path = $ this ->getFilePath ($ keyword );
73+ $ tmp_path = $ file_path . ".tmp " ;
7374 // echo "<br>DEBUG SET: ".$keyword." - ".$value." - ".$time."<br>";
7475 $ data = $ this ->encode ($ value );
7576
@@ -86,22 +87,33 @@ function driver_set($keyword, $value = "", $time = 300, $option = array() ) {
8687 }
8788 }
8889
89- if ($ toWrite == true ) {
90+ $ written = true ;
91+ /*
92+ * write to intent file to prevent race during read; race during write is ok
93+ * because first-to-lock wins and the file will exist before the writer attempts
94+ * to write.
95+ */
96+ if ($ toWrite == true && !@file_exists ($ tmp_path && !@file_exists ($ file_path ))) {
9097 try {
91- $ f = @fopen ($ file_path , "c " );
92- if (flock ($ f ,LOCK_EX | LOCK_NB )) { //got a lock to write;
93- fwrite ($ f , $ data );
94- fflush ($ f );
95- flock ($ f ,LOCK_UN );
98+ $ f = @fopen ($ tmp_path , "c " );
99+ if ($ f ) {
100+ if (flock ($ f ,LOCK_EX | LOCK_NB )) {
101+ $ written = ($ written && fwrite ($ f , $ data ));
102+ $ written = ($ written && fflush ($ f ));
103+ $ written = ($ written && flock ($ f , LOCK_UN ));
96104 } else {
97105 //arguably the file is being written to so the job is done
106+ $ written = false ;
107+ }
108+ $ written = ($ written && @fclose ($ f ));
109+ $ written = ($ written && @rename ($ tmp_path ,$ file_path ));
98110 }
99- fclose ($ f );
100111 } catch (Exception $ e ) {
101112 // miss cache
102- return false ;
113+ $ written = false ;
103114 }
104115 }
116+ return $ written ;
105117 }
106118
107119 function driver_get ($ keyword , $ option = array ()) {
0 commit comments