Reputation: 773
I'm playing around with writing to file with Python:
import time
fo = open("foo.txt", "a+", 1)
while True:
fo.write("Some data to write");
time.sleep(.001)
If I execute this code, and than just manualy delete the "foo.txt" file, the process still writes somewhere.
What happens with the content? The process writes to file, but no file is available.
Upvotes: 3
Views: 4994
Reputation: 2949
From The Linux Programming Interface
by Michael Kerrisk
In addition to maintaining a link count for each i-node, the kernel also counts open file descriptions for the file (see Figure 5-2, on page 95). If the last link to a file is removed and any processes hold open descriptors referring to the file, the file won’t actually be deleted until all of the descriptors are closed.
Your script have opened the file, thus it holds a open descriptor referring to the file. System won't delete the file just after you have removed it by i.e. use of rm
command. But it will delete it after your script close the descriptor.
I have found reference in man, from man remove
:
remove() deletes a name from the filesystem. It calls unlink(2) for files, and rmdir(2) for directories.
If the removed name was the last link to a file and no processes have the file open, the file is deleted and the space it was using is made available for reuse.
If the name was the last link to a file, but any processes still have the file open, the file will remain in existence until the last file descriptor referring to it is closed.
Just as @oglu mentioned in his answer, this is not portable behavior. On Windows, you may chose whether it should be possible to remove the file that you have opened.
From CreateFile function at MSDN
FILE_SHARE_DELETE (0x00000004)
Enables subsequent open operations on a file or device to request delete access.
Otherwise, other processes cannot open the file or device if they request delete access.
If this flag is not specified, but the file or device has been opened for delete access, the function fails.
Note Delete access allows both delete and rename operations.
Upvotes: 8
Reputation: 2453
The actual question is what happens when a file descriptor is changed while writing, which is platform specific.
If you have a POSIX system, the FD remains open until the last consumer closes it, in which case the content cannot be accessed (the file is already unlinked).
If you have a windows system, I think you can't delete the file while it's being written (exclusive access).
Upvotes: 1