[英]read from a file which is deleted
I wrote a small program in C where I opened a file successfuly, then called sleep for 20 sec. 我用C编写了一个小程序,在其中成功打开了一个文件,然后调用sleep保持20秒钟。 In that 20 sec I deleted the open file using rm from shell. 在那20秒内,我使用rm从shell删除了打开的文件。 After sleep the program reads the data successfully and prints it on screen. 睡眠后,程序成功读取数据并将其打印在屏幕上。
int bytes_read;
FILE *fp = fopen("/tmp/file", "r");
sleep(20);
bytes_read = fread(buf, 1, 5, fp);
buf[bytes_read] = '\0';
printf("%s", buf);
I expected it to read 0 bytes, but it prints the actual data in the file. 我希望它读取0字节,但它将在文件中打印实际数据。 What is the explanation behind this behaviour. 这种行为背后的解释是什么。
In linux and other POSIX systems you don't delete files. 在Linux和其他POSIX系统中,您不会删除文件。 You just remove an inode from a directory. 您只需从目录中删除一个索引节点。 As long as there is a file descriptor open on a file it will not be deleted. 只要在文件上打开了文件描述符,它就不会被删除。 Only when the last link to the inode and the last open file descriptor went away. 仅当指向索引节点的最后一个链接和最后打开的文件描述符消失时。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.