簡體   English   中英

在磁盤上分配文件而不清零

[英]Allocate file on disk without zeroing

我需要分配大文件而不將其內容清零。 我正在執行以下步驟: 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);
}

但僅適用於超級用戶!

顯然,這是MacOSX。

您可以嘗試將ftruncate呼叫替換為

fcntl(ofd, F_SETSIZE, &size);

(注意需要root特權,並且可能會創建一個安全漏洞,因為它可能提供對以前存在的舊文件內容的訪問權限,因此必須格外小心。您不關心的“臟文件內容”實際上可能是用戶的他一周前刪除的銀行帳戶密碼...)

MacOS X並不真正支持稀疏文件-它確實創建和維護它們,但是其文件系統驅動程序非常渴望盡快填補漏洞。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM