为什么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,size); //printf("itak: %d,errno: %d (%s)n",result,errno,strerror(errno)); int result = posix_fallocate(fd,size); printf("itak: %d,strerror(result)); } else { printf("failed opening filen"); } } else { printf("Usage blahn"); } } 这是我用来测试我的假设的简单版本的/usr/bin/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,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()在没有足够的情况下创建文件 解决方法
阅读“man 2 fallocate”,在磁盘空间不足的情况下,不保证库调用的行为,除了它将返回-1并且错误将是ENOSPC.
在POSIX.1-2001中,对posix_fallocate调用没有任何无副作用的要求. 因此,如果愿意,实现有权创建一个半大小的文件. 引擎盖下可能发生的事情是,从文件系统请求一定大小的空间并将其放入文件中.然后请求另一个块,依此类推,直到文件足够大以满足调用者的需要.因此,如果文件系统中途耗尽空间,则会留下大小小于请求的文件. 你只需按原样处理呼叫的行为;你不能改变实现代码(好吧,你可以通过提交补丁!).更改程序以正确处理所有允许的故障模式要容易得多. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |