Search code examples
clinuxfile-handlingtemp

What is the best way to create a non-persistent file in linux


In my application, I have a C process created which will be re-spawned if the process dies. Now I have a requirement to know if the process is spawned for the first time(after system reboot), due to which function X will be called, or if the process got re-spawned after a crash(runtime) due to which function Y will be called.

I tried creating temp files by the use of command mktemp() but the files seemed to be persistent even after the reboot.

So what would be best way to do it?


Solution

  • mktemp creates files in /tmp (by default). In many distributions, /tmp is persistent (i.e. disk-backed, not memory-backed).

    What you are looking for is to create a file in a memory-backed mount. Typically these are the tmpfs mounts. For example, on my Arch Linux laptop, my tmpfs mounts are:

    $ mount | grep tmpfs
    [..]
    run on /run type tmpfs (rw,nosuid,nodev,relatime,mode=755)
    shm on /dev/shm type tmpfs (rw,nosuid,nodev,noexec,relatime)
    

    So on this system, I can open and write to files in /dev/shm/ on /run and they will be backed by my memory, they won't persist across boots and the access will be fast and cheap.

    Back to your question, it seems that you can change the directory used by mktemp. Quoting the man page:

    -p DIR, --tmpdir[=DIR]
                  interpret  TEMPLATE relative to DIR; if DIR is not specified, use $TMPDIR if set, else /tmp.  With this option, TEMPLATE must not be
                  an absolute name; unlike with -t, TEMPLATE may contain slashes, but mktemp creates only the final component
    

    EDIT - few more things:

    • this is all distribution-dependent; other distributions may mount tmpfs at /tmp.
    • interestingly, /dev/shm is where shared memory objects created with shm_open are stored.