Alex Rivera | Logout

Guaranteed file deletion upon program termination (C/C++)

Asked 2009-01-22T23:53:59.443
22

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:

  1. 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.
  2. 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.
  3. atexit(3): apparently useless, since it isn't called during abnormal termination (e.g. via a signal).
  4. 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 r

Edit
Report

1 Answer

2

Do you really need the name to remain visible?

Suppose you take the option of immediately unlinking the file. Then:

  • 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).

    You can still debug on a deleted file, since it will still be visible under /proc/$pid/fd/. As long as you know the pids of your processes, enumerating their open files should be easy.

  • the names need to remain visible during normal operation because they are shared between programs.

    You can still share the deleted open file between processes by passing around the file descriptor over Unix domain sockets. See Portable way to pass file descriptor between different processes for more information.

answered 2012-08-14T00:35:40.837

Your Answer