c++ - Fsync 太快?

标签 c++ c linux filesystems

我对大文件 ftruncatefsync 操作感到惊讶。我编写了一个程序,在 Linux 64 位系统上创建一个空文件,将其截断为 0xffffffff 字节,然后 fsync 它。

在所有操作之后,文件被正确地创建为这个长度。

我看到 ftruncate 花费了大约 1442 微秒,而 fsync 只花费了 4 微秒。

正常这么高性能吗?是否真的将所有字节都写入了光盘?如果没有,我如何确保同步?

#include <sys/time.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <iostream>

static const size_t __tamFile__ = 0xffffffff;

int main(int, char **)
{
    std::string fichero("./testTruncate.dat");

    unlink(fichero.c_str());

    int fd = open(fichero.c_str(), O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
    if (fd != -1)
    {
        struct timeval t1, t2;

        timerclear(&t1);
        timerclear(&t2);

        gettimeofday(&t1, NULL);
        ftruncate(fd, __tamFile__);
        gettimeofday(&t2, NULL);

        unsigned long long msecTruncate = static_cast<unsigned long long>((((t2.tv_sec * 1E6) + t2.tv_usec) - ((t1.tv_sec * 1E6) + t1.tv_usec))) ;

        gettimeofday(&t1, NULL);
        fdatasync(fd);
        gettimeofday(&t2, NULL);

        unsigned long long msecFsync = static_cast<unsigned long long>((((t2.tv_sec * 1E6) + t2.tv_usec) - ((t1.tv_sec * 1E6) + t1.tv_usec))) ;

        std::cout << "Total microsec truncate: " << msecTruncate << std::endl;
        std::cout << "Total microsec fsync: " << msecFsync << std::endl;

        close(fd);
    }
    return 0;
}

最佳答案

I wrote a program that create an empty file on a Linux 64 bits system, truncate it to 0xffffffff bytes and after, fsync it.

除非您向其中写入内容,否则该文件极有可能包含漏洞。

来自 TLPI:

What happens if a program seeks past the end of a file, and then performs I/O? A call to read() will return 0, indicating end-of-file. Somewhat surprisingly, it is possible to write bytes at an arbitrary point past the end of the file.

The space in between the previous end of the file and the newly written bytes is referred to as a file hole. From a programming point of view, the bytes in a hole exist, and reading from the hole returns a buffer of bytes containing 0 (null bytes).

File holes don’t, however, take up any disk space. The file system doesn’t allocate any disk blocks for a hole until, at some later point, data is written into it.

关于c++ - Fsync 太快?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10750655/

相关文章:

c++ - 在 SOCK_RAW 通信中创建以太网帧

c++ - Int类型类的运算符重载

C 程序无法在 Visual Studio 2010 中编译

c - Linux shell 脚本错误

c++ - 为 beaglebone black 交叉编译 c++ openCV 应用程序时出现问题

regex - grep 可以删除上下文,但不能删除整行吗?

c++ - 黑莓 10 中 ScrollView 的视口(viewport)大小调整

c++ - SFINAE 未检测到 T::reference

c++ - 在不使用静态成员的情况下跨对象树共享数据的策略

linux - 为什么 CUDA 对 bashrc 中的变量声明感到困惑?