I have a question that why write() system call still succeed to write something after I have deleted the target file from shell?
When I delete the file after the first several success writes, I was expecting to see write() fails but it doesn't and I don't know where does it write to.
Can anyone explain this to me, thanks!!
int fd = open ("./test.txt", O_CREAT | O_RDWR | O_APPEND, 0666);
if (fd == -1)
error_and_exit ("open() failed");
ssize_t written = 0;
char buf[] = "apple\n";
while (true)
{
printf ("perform write...\n");
written = write (fd, buf, sizeof(buf));
if (written <= 0)
error_and_exit ("write failed");
printf ("=> wrote %d bytes\n", written);
printf ("sleep %d...\n\n", SLEEP_TIME);
sleep (SLEEP_TIME);
}
A file is not physically deleted (at the inode level, if the file system has inodes) until the last open file descriptor closes on the file, even if there are no name references left for the file (because its last name has been unlinked, aka deleted). This is how temporary but anonymous files are created for POSIX (Unix) systems, by creating the file and then deleting its name.
Note that if you have a daemon process that keeps a log file open, the daemon is likely to keep writing to the old file (not the new one) and the space won't be released until the daemon does terminate (or, more accurately, closes the file descriptor for the old log file).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With