6

我需要分配大文件而不将其内容归零。我正在制作fopen => ftruncate => fclose => mmap => (...work...) => munmap具有巨大文件大小(数百 GB)的这些步骤。应用程序在系统尝试将文件字节归零时挂起几分钟 - 恕我直言,因为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回答,用这几行替换了我所有与 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);
}

但仅适用于超级用户!

4

1 回答 1

5

这显然是 MacOS X。

您可以尝试将ftruncate呼叫替换为

fcntl(ofd, F_SETSIZE, &size);

(注意需要 root 权限并且可能会造成安全漏洞,因为它可能会提供对以前存在的旧文件内容的访问权限,因此必须非常小心地处理。您不关心的“脏文件内容”实际上可能是用户的他一周前删除的银行账户密码……)

MacOS X 并不真正支持稀疏文件——它确实创建和维护它们,但它的文件系统驱动程序非常渴望尽快填补这些漏洞。

于 2017-06-02T08:01:40.363 回答