ZetCode

PHP fsync 函数

最后修改于 2025 年 4 月 3 日

PHP fsync 函数强制将文件更改同步到磁盘。它确保所有缓冲的修改都已物理写入存储。

基本定义

fsync 函数将文件内存中的状态与存储设备同步。它接受一个文件指针资源并返回一个布尔值表示成功。

语法:fsync(resource $stream): bool。此函数对于处理关键文件操作的数据完整性至关重要。

基本的 fsync 示例

这显示了 fsync 最简单的用法,以确保文件更改已写入磁盘。

basic_fsync.php
<?php

declare(strict_types=1);

$file = fopen('important.log', 'w');
fwrite($file, 'Critical data');
$success = fsync($file);
fclose($file);

var_dump($success); // Outputs: bool(true)

这可以确保“关键数据”在继续之前已物理写入磁盘。如果同步成功,该函数将返回 true。

错误处理示例

这演示了在使用 fsync 时正确的错误处理。

fsync_error.php
<?php

declare(strict_types=1);

$file = fopen('data.log', 'w');

if ($file === false) {
    die('Failed to open file');
}

fwrite($file, 'Important content');

if (!fsync($file)) {
    die('Failed to sync file to disk');
}

fclose($file);

此示例同时检查了文件打开和 fsync 成功。对于关键文件操作,正确的错误处理至关重要。

与 fflush 结合使用

fsync 通常与 fflush 一起使用以获得完全控制。

fsync_fflush.php
<?php

declare(strict_types=1);

$file = fopen('transaction.log', 'a');

fwrite($file, 'New transaction data' . PHP_EOL);
fflush($file); // Flush PHP buffers
$synced = fsync($file); // Force OS to write to disk

if (!$synced) {
    error_log('Disk sync failed');
}

fclose($file);

fflush 清空 PHP 的缓冲区,而 fsync 确保操作系统将其写入磁盘。这种组合可提供最大的数据完整性。

数据库事务示例

在写入数据库事务日志时使用 fsync

db_transaction.php
<?php

declare(strict_types=1);

function logTransaction(string $data): void {
    $logFile = fopen('transactions.log', 'a');
    
    fwrite($logFile, date('Y-m-d H:i:s') . ': ' . $data . PHP_EOL);
    
    if (!fsync($logFile)) {
        throw new RuntimeException('Failed to sync transaction log');
    }
    
    fclose($logFile);
}

logTransaction('User payment processed');

这确保在继续之前事务日志已物理写入。关键的金融系统通常采用这种方法。

性能注意事项

fsync 对性能有显著影响,因为它会等待磁盘写入。

performance.php
<?php

declare(strict_types=1);

$start = microtime(true);
$file = fopen('largefile.dat', 'w');

// Write 1MB of data
fwrite($file, str_repeat('x', 1024 * 1024));

fsync($file); // This will block until write completes
fclose($file);

$duration = microtime(true) - $start;
echo "Operation took: " . round($duration, 3) . " seconds";

这表明 fsync 如何影响性能。请仅在关键操作中谨慎使用。

最佳实践

来源

PHP fsync 文档

本教程涵盖了 PHP fsync 函数,并提供了实际示例,展示了它在不同场景下的用法。

作者

我叫 Jan Bodnar,是一名充满激情的程序员,拥有丰富的编程经验。我从 2007 年开始撰写编程文章。至今,我已撰写了 1400 多篇文章和 8 本电子书。我在编程教学方面拥有十多年的经验。

列出 所有 PHP 文件系统函数