PHP并发写文件数据串行的问题

写日志代码:

$dir = rtrim($dir, '/') . '/' . ltrim($logFile, '/');

// 自动创建不存在的目录
$directory = dirname($dir);
if (!is_dir($directory)) {
    $oldUmask = umask(0);
    mkdir($directory, 0777, true);
    umask($oldUmask);
}   

$fd = fopen($dir, "a+");
if (!$fd) {
    error_log("Logger: Cannot open file ($dir)");
    return false;
}   

$logData = implode("\t", $data);

fwrite($fd, $logData. "\n");
fclose($fd);

同事反馈上报的日志格式错误,看了下日志,发现居然有串行的现象。

数据串行

搜索一番才知道,当写的数据过大时,可能会产生串行的问题。

If handle was fopen()ed in append mode, fwrite()s are atomic (unless the size of string exceeds the filesystem's block size, on some platforms, and as long as the file is on a local filesystem). That is, there is no need to flock() a resource before calling fwrite(); all of the data will be written without interruption.

参考资料:
封装php的Log类

标签: none

添加新评论