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

前端 未结 8 1258
长发绾君心
长发绾君心 2020-12-14 02:16

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 terminat

相关标签:
8条回答
  • 2020-12-14 03:18
    • Have a book-keeping directory for temporary files under your dot-directory.
    • When creating a temp-file, first create book-keeping file into the book-keeping directory that contains path or UUID to your to-be temp file.
    • Create that temp file.
    • When temp-file is deleted, then delete the book-keeping file.
    • When the program starts, scan the book-keeping directory for any files containing paths to temporary files and try to delete them if found, them delete book-keeping files.
    • (Log noisily if any step fails.)

    I don't see ways to do it any way simpler. This is the boilerplate any production quality program must go through; +500 lines easily.

    0 讨论(0)
  • 2020-12-14 03:20

    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.

    0 讨论(0)
提交回复
热议问题