考虑我有以下代码:
#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 和正确的 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
正如您所看到的,它在 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() 创建文件以防万一