Dontstoptilyougetenoughphp多线程上下文中安全写文件实现代码

Dontstoptilyougetenoughphp多线程上下文中安全写文件实现代码

内容导读

收集整理的这篇技术教程文章主要介绍了Dontstoptilyougetenoughphp多线程上下文中安全写文件实现代码,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1980字,纯文字阅读大概需要3分钟

内容图文

代码如下:


/**
* @usage: used to offer safe file write operation in multiple threads context, arbitory file type
* @author: Rocky Zhang
* @time: Nov. 11 2009
* @demo[0]: $handler = mfopen($file, 'a+');
* mfwrite($handler, $str);
*/
function mfopen($file, $mode='w+') {
$tempfile = generateTempfile('./tempdir', $file);
preg_match('/b/i', $mode) || ($mode .= 'b'); // 'b' is recommended
if (preg_match('/w|a/i', $mode) && !is_writable($file)) {
exit("{$file} is not writable!");
}
$filemtime = $filemtime2 = 0;
$tempdir = dirname($tempfile);
is_dir($tempdir) || mkdir($tempdir, 0777);
do { // do-while used to avoid modify in a long time copy
clearstatcache();
$filemtime = filemtime($file);
copy($file, $tempfile);
$filemtime2 = filemtime($file);
} while ( ($filemtime2 - $filemtime) != 0 );
if (!$handler = fopen($tempfile, $mode)) {
exit('Fail on opening tempfile, write authentication is must on temporary dir!');
}
return array(0=>$handler, 1=>$filemtime, 2=>$file, 3=>$tempfile, 4=>$mode);
}
// I do think that this function should be optimized further
function mfwrite(&$handler, $str='') {
if (strlen($str) > 0) {
$num = fwrite($handler[0], $str);
fflush($handler[0]);
}
clearstatcache();
$mtime = filemtime($handler[2]);
if ( $mtime == $handler[1] ) { // compare between source file and temporary file
if ( $num && $num > 0 ) { // temporary file has been updated, copy to source file
copy($handler[3], $handler[2]) || exit;
$handler[1] = filemtime($handler[3]);
touch($handler[2], $handler[1], $handler[1]);
}
} else { // source file has been modified, load source file to temporary file
copy($handler[2], $handler[3]) || exit;
touch($handler[3], $mtime, $mtime);
$handler[1] = $mtime;
}
}
function generateTempfile($tempdir='tempdir', $file) {
$rand = md5(microtime());
return "{$tempdir}/{$rand}_".$file;
}
?>

以上就介绍了Dont stop til you get enough php 多线程上下文中安全写文件实现代码,包括了Dont stop til you get enough方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

内容总结

以上是为您收集整理的Dontstoptilyougetenoughphp多线程上下文中安全写文件实现代码全部内容,希望文章能够帮你解决Dontstoptilyougetenoughphp多线程上下文中安全写文件实现代码所遇到的程序开发问题。 如果觉得技术教程内容还不错,欢迎将网站推荐给程序员好友。

内容备注

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。



联系我们

在线咨询:点击这里给我发消息

邮件:w420220301@qq.com