title: Guaranteed file deletion upon program termination (C/C++)
body: <p>Win32's <a href="http://msdn.microsoft.com/en-us/library/aa363858(VS.85).aspx" rel="noreferrer"><code>CreateFile</code></a> has <code>FILE_FLAG_DELETE_ON_CLOSE</code>, but I'm on Linux.</p>
  
  <p>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.</p>
  
  <p>I know about RAII.  I know about signals.  I know about <code>atexit(3)</code>.  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:</p>
  
  <ol>
  <li>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.</li>
  <li>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 <code>sigaction(2)</code> to cope...but haven't put enough thought into this possibility yet.</li>
  <li><code>atexit(3)</code>: apparently useless, since it isn't called during abnormal termination (e.g. via a signal).</li>
  <li>preemptive <code>unlink(2)</code>: this is pretty good except that I need the file to remain visible in the filesystem (otherwise the system is harder to monitor/troubleshoot).</li>
  </ol>
  
  <p>What would you do here?</p>
  
  <p><strong>Further Explanation</strong></p>
  
  <p>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 <code>mq_open()</code>.  It can be closed via <code>mq_close()</code> or <code>close()</code> (the former is an alias for the latter on my system).  It can be removed from the system via <code>mq_unlink()</code>.  All of this makes it analogous to a regular file, <em>except</em> that I cannot choose the directory in which the file resides.  This makes the current most popular answer (placing the file in <code>/tmp</code>) unworkable, because the "file" is created by the system in a virtual filesystem with very limited capacity.  (I've mounted the virtual filesystem in <code>/dev/mqueue</code>, following the example in <code>man mq_overview</code>) .</p>
  
  <p>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.</p>