Sharing the Memories

Shared memory is one of those things that most applications don’t use but can be very useful. I am only going to cover its implementation on Linux, how to size it, what its properties are and how do abuse it. What I am not going to cover are the “shm_*” functions which allows applications to share memory between them. While these are implemented on top of shared memory, that is an entirely different subject and well covered online or in various books (I can recommend “Unix Network Programming – Volume 2″ by Stevens.)

Shared memory on Linux is implememted as a file system mounted on “/dev/shm”. By default this partition is set to half of available RAM when the operating system is installed. So a system with 4GB of RAM will have a shared memory partition of 2GB.

This can be easily changed in /etc/fstab as follows:

tmpfs /dev/shm tmpfs size=4G 0 0

All that needs to be done is to change the size variable to whatever size you want your shared memory partition to be, and unmount and remount the file system. Two things to note: this memory is not actually allocated until you use it so won’t have any impact on your system, and the size of the shared memory partition cannot exceed the swap space available. I generally set my swap space to equal the amount of RAM available, though for special configurations I will set it to twice that.

Given that the shared memory is presented as a file system, shouldn’t we be able to use it as such. Well we can, and the best way I like to think about it is as a RAM disk. I can write stuff there and the files will be stored in RAM (not always, more on that later,) and I can access that stuff at a later date.

There are two caveats though. The first is that this file system gets cleaned upon reboot, so don’t put anything there which you will want to access after the system is rebooted, use the regular file system for that. The second caveat is that this data has to co-exist with everything else the operating system is running, so you probably would not want use all the space available if you want to maintain good performance. If the operating system needs space, it will not hesitate to write pages from shared memory out to swap (which is probably why the default file system size is set to half of available RAM.)

All that being said, the shared memory partition can be very useful as a storage space for temporary files, or for static files which you need to access a lot. The operating system will do its best to keep that data in memory, giving you fast access to it.


Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: