1

I have a program which uses temporary files, created using the mkstemps function. The files are created inside the /tmp directory.

Does these files get removed automatically on program exit?

I'm wondering if my program should remove these files before exit. If they aren't removed automatically, is it acceptable to not remove them, and have them remain in /tmp? Or is it better practice to remove them using unlink or remove before program exit?

3

Files created by one of the mkstemp family of functions aren’t automatically deleted on program exit. Depending on their contents, you can choose to leave them in /tmp, which is typically cleaned up periodically, but that’s somewhat poor form.

There are two main ways you can handle this cleanly:

  • if no other process needs to be able to open the temporary file, or you can deal with this by passing file descriptors, then you can delete the file immediately after mkstemps returns — the file will still exist, but it will no longer appear in directory listings, and it will be deleted as soon as you close the file descriptor;
  • otherwise, register an exit function with atexit which deletes the file.
|improve this answer|||||
3

You should remove them immediately after creating them with open(O_CREAT) or similar, and only use them via the returned file descriptor.

Higher level interfaces like tmpfile(3) will do that for you, and may even use better approaches, like O_TMPFILE on Linux (see the open(2) manpage for a description).

Removing them "before exit" is broken, because your program may terminate abnormally, before being able to remove them.

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.