Why does fallocate () on linux create a non-empty file if it doesn't have enough space?

Consider the following code snippet:

#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");
    }


}

/usr/bin/fallocate , . , , , -1 , . , -1, ​​, - . , , , - ( ) . fallocate(), , , , , , .

, fallocate() posix_fallocate() save, , .

, , - . , , 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

, , 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

( " " )

ext4 tmpfs . gentoo linux, ​​3.18. SLES12.

: /usr/bin/fallocate fallocate() ,

+4
1

"man 2 fallocate", , , , -1, ENOSPC.

POSIX.1-2001 posix_fallocate.

, , .

, , , , . , . , , .

; (, , !). .

+1

Source: https://habr.com/ru/post/1609103/


All Articles