Skip to content
Snippets Groups Projects
TODO 1.59 KiB
Newer Older
Eric Rasmussen's avatar
Eric Rasmussen committed

Patrick O'Lone suggests the following idea which sounds interesting to
add as an optional mode of Cache_Lite class. 
(still not tested in the Cache_Lite context)

-------------------------------------------------------------------------
If you use the flags:

ignore_user_abort(true);

$fd = dio_open($szFilename, O_CREATE | O_EXCL | O_TRUNC | O_WRONLY,
0644);
if (is_resource($fd)) {

   dio_fcntl($fd, F_SETLKW, array('type' => F_WRLCK));
   dio_write($fd, $szBuffer);
   dio_fcntl($fd, F_SETLK, array('type' => F_UNLCK));
   dio_close($fd);

}

ignore_user_abort(false);

Only the first process will attempt to create a file. Additional
processes will see that a file already exists (at the system level), and
will fail. Another thing to note is that the file descriptor must be
opened using dio_open(), and certain features, like fgets() won't work
with it. If your just doing a raw write, dio_write() should be just
fine. The dio_read() function should be used like:

$fd = dio_open($szFilename, O_RDONLY|O_NONBLOCK, 0644);
if (is_resource($fd)) {

   dio_fcntl($fd, F_SETLKW, array('type' => F_RDLCK));
   $szBuffer = dio_read($fd, filesize($szFilename));
   dio_fcntl($fd, F_SETLK, array('type' => F_UNLCK));
   dio_close($fd);

}

You still use locking to ensure that a write process can finish before
another attempts to read the file. We also set non-blocking mode in read
mode so that multiple readers can access the same resource at the same
time. NOTE: Direct I/O support must be compiled into PHP for these
features to work (--enable-dio).
-------------------------------------------------------------------------