gpt4 book ai didi

c++ - Fsync 太快?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:45:53 25 4
gpt4 key购买 nike

我对大文件 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com