为什么linux上的fallocate()在没有足够空间时会创建一个非空文件?

Sco*_*ger 5 c linux fallocate

考虑我有以下代码:

#define _GNU_SOURCE             /* See feature_test_macros(7) */
#include <fcntl.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>

int main(int argc, char** argv) {

    if (argc > 2) {
        int fd = open(argv[1], O_CREAT|O_WRONLY, 0777);
        size_t size = atoi(argv[2]);

        if (fd > 0) {

            //int result = fallocate(fd, 0, 0, size);
            //printf("itak: %d, errno: %d (%s)\n", result, errno, strerror(errno));
            int result = posix_fallocate(fd, 0, size);
            printf("itak: %d, errno: %d (%s)\n", result, result, strerror(result));

        } else {
            printf("failed opening file\n");
        }

    } else {
        printf("Usage blah\n");
    }


}
Run Code Online (Sandbox Code Playgroud)

这是我用来测试我的假设的简单版本的/ usr/bin/fallocate.我发现如果我使用它创建一个大于文件系统可用空间的文件,它将返回-1和一个正确的errno,但仍会创建一个允许的最大大小的文件.这对我来说似乎很奇怪,因为命令显式返回-1,这应该是一个失败的信号,但它仍然做了一些事情.而且它不是我要求的 - 它创建了一个未知的文件(目前我运行它)大小.如果我使用fallocate()来保留一些空间,我不知道,小猫照片如果它保留的空间比我要求的少,对我来说就没用了.

是的,fallocate()和posix_fallocate()表现为保存方式,我检查了两个,你可以看到.

当然我以为我做错了什么.因为如果你在编程时遇到问题,那就是99.9%的情况.所以我尝试了/ usr/bin/fallocate实用程序,是的,它"失败",但仍然创建了一个文件.

以下是我运行该实用程序的示例:

rakul@lucky-star /tmp $ strace fallocate -l 10G /tmp/test 2>&1 | grep fallocate
execve("/usr/bin/fallocate", ["fallocate", "-l", "10G", "/tmp/test"], [/* 47 vars */]) = 0
fallocate(3, 0, 0, 10737418240)         = -1 ENOSPC (No space left on device)
write(2, "fallocate: ", 11fallocate: )             = 11
write(2, "fallocate failed", 16fallocate failed)        = 16
rakul@lucky-star /tmp $ ls -l /tmp/test
-rw-r--r-- 1 rakul rakul 9794732032 ??? 26 19:15 /tmp/test
rakul@lucky-star
Run Code Online (Sandbox Code Playgroud)

正如您所看到的那样,在fallocate()调用中没有设置特定的模式,它失败了,但是文件被创建了,意外的大小.

我发现互联网上的一些人看到了相反的行为:

rxxxx@home/tmp> fallocate -l 10G test.img
fallocate: fallocate failed: ?? ?????????? ?? ???????? ?????????? ?????
rxxxx@home/tmp> ls -l test.img 
-rw-r--r-- 1 rogue rogue 0 ??? 26 17:36 test.img
Run Code Online (Sandbox Code Playgroud)

(俄语中说"没有足够的空间")

我尝试过ext4和tmpfs,结果相同.我有gentoo linux,3.18内核.但最初我在最新的SLES12上看到了这个问题.

我的问题是:为什么会有不同的结果以及我如何防止/ usr/bin/fallocate或fallocate()在没有足够的情况下创建文件

Bor*_*lid 2

阅读“man 2 Fallocate”,在磁盘空间不足的情况下,不保证库调用的行为,除了它将返回 -1 并且错误将为ENOSPC

在 POSIX.1-2001 中,调用也没有提出无副作用的要求posix_fallocate

因此,如果实现愿意的话,它有权创建一半大小的文件。

幕后可能发生的事情是从文件系统请求一定大小的空间块并将其放入文件中。然后请求另一个块,依此类推,直到文件足够大以满足调用者的需要。因此,如果文件系统中途空间不足,则会留下小于请求大小的文件。

您只需按原样处理调用的行为即可;您无法更改实现代码(好吧,您可以通过提交补丁来更改!)。更改程序以正确处理所有允许的故障模式要容易得多。