【发布时间】:2017-11-03 12:30:54
【问题描述】:
我需要分配大文件而不将其内容归零。我正在使用巨大的文件大小(数百 GB)生成此步骤fopen => ftruncate => fclose => mmap => (...work...) => munmap。应用程序在系统尝试将文件字节归零时挂起几分钟 - 恕我直言,因为 ftruncate 的使用。
ftruncate(ofd, 0);
#ifdef HAVE_FALLOCATE
int ret = fallocate(ofd, 0, 0, cache_size);
if (ret == -1) {
printf("Failed to expand file to size %llu (errno %d - %s).\n", cache_size, errno, strerror(errno));
exit(-1);
}
#elif defined(HAVE_POSIX_FALLOCATE)
int ret = posix_fallocate(ofd, 0, cache_size);
if (ret == -1) {
printf("Failed to expand file to size %llu (errno %d - %s).\n", cache_size, errno, strerror(errno));
exit(-1);
}
#elif defined(__APPLE__)
fstore_t store = {F_ALLOCATECONTIG, F_PEOFPOSMODE, 0, cache_size, 0};
int ret = fcntl(ofd, F_PREALLOCATE, &store);
if (ret == -1) {
store.fst_flags = F_ALLOCATEALL;
ret = fcntl(ofd, F_PREALLOCATE, &store);
}
if (ret == -1) { // read fcntl docs - must test against -1
printf("Failed to expand file to size %llu (errno %d - %s).\n", cache_size, errno, strerror(errno));
exit(-1);
}
struct stat sb;
ret = fstat(ofd, &sb);
if (ret != 0) {
printf("Failed to write to file to establish the size.\n");
exit(-1);
}
//ftruncate(ofd, cache_size); <-- [1]
#endif
它似乎不适用于注释行[1]。但是取消注释这一行会产生我试图避免的文件归零。在写之前我真的不在乎脏文件内容。我只是想避免挂起应用程序终止。
解决方案:
根据@torfo的answer,用这几行替换了我所有与Apple相关的代码:
unsigned long long result_size = cache_size;
int ret = fcntl(ofd, F_SETSIZE, &result_size);
if(ret == -1) {
printf("Failed set size %llu (errno %d - %s).\n", cache_size, errno, strerror(errno));
exit(-1);
}
但仅适用于超级用户!
【问题讨论】:
-
deleted(
ftruncate()也应该创建一个稀疏文件,所以看起来你的操作系统/文件系统不支持稀疏文件) -
如果您需要制作一个大文件而不将其内容归零,只需
ftruncate而无需执行其他操作。如果您的文件系统支持它,那将创建一个稀疏文件。fallocate和其他调用会做相反的事情,它们会预先分配磁盘块并将其归零。写入稀疏文件时可能会出现磁盘空间不足的风险,但不会浪费时间将其归零。 -
@Art 应用与
ftruncate在通过Ctrl+C终止时挂起几分钟。 -
注意分配以前使用的磁盘空间而不将其归零且没有“稀疏”会产生潜在的安全漏洞。
标签: c macos posix fcntl fallocate