0

I have an application that does a lot of forking, and every fork uses quite a lot of temp disk space. Currently, all of this space is used in /tmp. For various reasons, I want to clean up these tmp files asap after the process dies, preferably instantly.

The problem is that in many cases, the proc are terminated irregularly; hence the process itself should not be responsible for cleaning up its tmp files. What would be a nice way to set this up so that tmp files are removed when the process dies?

I was thinking about writing files to /tmp/myapp/$pid/ and then having a cron job every second or so that searches for directories /tmp/myapp/$pid/ and unlinks the ones for which there is no active process with that ID. But that might create a lot of overhead. Also for fun I tried if I could actually put the dir inside of the proc mkdir /proc/12345/tmp but that doesn't fly either :-)

1
  • Do you have access to the source code for this program? I'm guessing not if you need to go about doing this. Instead of cron look into inotify to see if you can monitor for the creation of /tmp/app/pid# and then register a job to clean it up in a few minutes (hours, days, etc)
    – Huckle
    Apr 25, 2012 at 23:35

1 Answer 1

1

If you have access to the source code, you can use tmpfile() function to create an "anomymous" temporary file - a file is created and immediately unlinked - the application is able to write to it but as soon as the file is closed the space occupied by the file is freed. This is a common way to create temporary files in Unix, as I understand.

SYNOPSIS

   #include <stdio.h>

   FILE *tmpfile(void);

DESCRIPTION

   The  tmpfile()  function  opens  a unique temporary file in binary read/write (w+b) mode.  The file will be
   automatically deleted when it is closed or the program terminates.

If you don't have access to the source code you may try to just delete everything from /tmp/myapp/$pid/ periodically - the process will still be able to write to the file even if it's unlinked from the directory, but again the disk space will be freed as soon as the last file handle is closed.

The above approaches would not work if any tempfiles are opened, closed and then opened again or if they're used by multiple processes.

Related question on stackoverflow: https://stackoverflow.com/questions/9889277/how-to-create-temporary-files-on-linux-that-will-automatically-clean-up-after-th

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .