k06*_*06a 5 c macos posix fcntl fallocate
我需要分配大文件而不归零它的内容.我正在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
Run Code Online (Sandbox Code Playgroud)
它似乎不适用于评论行[1].但取消注释这一行会产生文件清零,我试图避免这种情况.在写之前我真的不在乎脏文件内容.我只是想避免挂在应用终止上.
解:
根据@torfo的回答,用以下几行替换了所有与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);
}
Run Code Online (Sandbox Code Playgroud)
但只适用于超级用户!
这显然是MacOS X.
您可以尝试使用替换ftruncate呼叫
fcntl(ofd, F_SETSIZE, &size);
Run Code Online (Sandbox Code Playgroud)
(注意需要root权限并且可能会创建一个安全漏洞,因为它可能提供对以前存在的旧文件内容的访问,因此必须非常谨慎地处理.您不关心的"脏文件内容"实际上可能是用户的他一周前删除的银行帐户密码...)
MacOS X并不真正支持稀疏文件 - 它确实创建并维护它们,但它的文件系统驱动程序非常渴望尽快填补漏洞.
| 归档时间: |
|
| 查看次数: |
299 次 |
| 最近记录: |