Win32's CreateFile
has FILE_FLAG_DELETE_ON_CLOSE
, but I'm on Linux.
I want to open a temporary file which will always be deleted upon program termination. I could understand that in the case of a program crash it may not be practical to guarantee this, but in any other case I'd like it to work.
I know about RAII. I know about signals. I know about atexit(3)
. I know I can open the file and delete it immediately and the file will remain accessible until the file descriptor is closed (which even handles a crash). None of these seem like a complete and straightforward solution:
- RAII: been there, done that: I have an object whose destructor deletes the file, but the destructor is not called if the program is terminated by a signal.
- signals: I'm writing a low-level library which makes registering a signal handler a tricky proposition. For example, what if the application uses signals itself? I don't want to step on any toes. I might consider some clever use of
sigaction(2)
to cope...but haven't put enough thought into this possibility yet. atexit(3)
: apparently useless, since it isn't called during abnormal termination (e.g. via a signal).- preemptive
unlink(2)
: this is pretty good except that I need the file to remain visible in the filesystem (otherwise the system is harder to monitor/troubleshoot).
What would you do here?
Further Explanation
I elided one detail in my original post which I now realize I should have included. The "file" in this case is not strictly a normal file, but rather is a POSIX Message Queue. I create it via mq_open()
. It can be closed via mq_close()
or close()
(the former is an alias for the latter on my system). It can be removed from the system via mq_unlink()
. All of this makes it analogous to a regular file, except that I cannot choose the directory in which the file resides. This makes the current most popular answer (placing the file in /tmp
) unworkable, because the "file" is created by the system in a virtual filesystem with very limited capacity. (I've mounted the virtual filesystem in /dev/mqueue
, following the example in man mq_overview
) .
This also explains why I need the name to remain visible (making the immediate-unlink approach unworkable): the "file" must be shared between two or more processes.
open(...)
, i.e., providing some other way an arbitrary process could obtain a file descriptor that refers to your file? You could implement something like this, or even this. – Dusk