Reputation: 1119
I wrote a small program in C where I opened a file successfuly, then called sleep for 20 sec. In that 20 sec I deleted the open file using rm from 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. What is the explanation behind this behaviour.
Upvotes: 1
Views: 589
Reputation: 78973
In linux and other POSIX systems you don't delete files. 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.
Upvotes: 12