I've been studying some Linux implementation and a question came up to my mind.
As far as I know, there is a bit which marks a file as a temporary file. When the process which generated that file dies, how does the kernel delete it? I've thinking that it might be related to the file descriptor table, but I'm not sure whatsoever.
If someone could give an explanation step-by-step, that would come in handy!
There's no bit that marks a file as a temporary file.
Every inode has a link count field, which is the number of directory entries that refer to the file. Every time you make a hard link to a file this count is increased, and when you remove a name it's decreased; when the count goes to zero, the file is deleted (the inode is marked as available, and all the data blocks are put on the free list).
When a file is opened in a process, a copy of the inode is kept in the kernel's file table, and the number of file handles that refer to it are added into the link count in this copy. When a process closes its file descriptor, the link count is decremented. The file isn't actually removed until this in-memory link count drops to zero. This is what keeps a file on disk while it's open, even if all the names are removed.
So when you create a temporary file, it performs the following steps:
At this point, the process can keep using the temporary file, but it can't be opened by another process because it has no name.
When the process closes the file handle, the link count goes to 0, and the file is deleted.
Recent versions of Linux have an O_TMPFILE
flag to open(2)
that automates this. Instead of specifying a filename, you just specify the directory, which is just used to find a filesystem to hold the file data. When this is used, it effectively does all 3 steps above in one call, but it never actually creates the filename anywhere (so race conditions and name conflicts are avoided).