/dev/shm is better than /tmp
Post
Cancel

/dev/shm is better than /tmp

One often has to use temporary files to store temporary data, and this is often done under UNIX using the /tmp directory (or /var/tmp directory). Well, it works, but the /tmp directory is a real directory on your hard drive (at least on Linux), and if you really need to use temporary stuff, it’s not really interesting to put it on your hard drive. Nowadays we have a lot of RAM memory. Why not using it for temporary files? This is where /dev/shm appears!

/dev/shm is a “virtual directory” that exists only in your RAM. Technically, it’s a normal directory but where part of your RAM is mounted, using a special filesystem known as tmpfs. This can be seen using mount:

1
2
$ mount | grep tmpfs
tmpfs on /dev/shm type tmpfs (rw)

You can use as much space here as the half of your total available RAM (by default, this can be changed but is probably not a good idea). I often use it for files that need to be actively seeked in, which is not hard-drive friendly at all. Of course, writing and reading to /dev/shm is blazing fast, as everything only takes place in RAM.

Now, don’t worry, all the /dev/shm space is not “exclusively reserved”, which means that, if only 1 MiB is used on it, only 1 MiB will be used in your RAM, not the whole half of your memory available. This can be seen as an automatically-adjusting area of memory, which stops to expand when it reaches the half of your physically installed RAM. Of course, when you switch off your machine, all the content of /dev/shm instantly disappears. Now, I really wonder how could I have lived without it…

Oh, and if you want to change the maximum amount of RAM which can be used by a tmpfs mount point, use this command:

1
# mount -o remount,size=64m /dev/shm

Which would limit the virtual filesystem to a maximum of 64 MiB, as reported by df:

1
2
3
$ df -h /dev/shm/
Filesystem            Size  Used Avail Use% Mounted on
tmpfs                  64M   36M   29M  56% /dev/shm
This post is licensed under CC BY 4.0 by the author.