Linux Memory and Processes

Use free to determine how much memory is being used, and how much is available.

Display memory usage in MB:

free -m

Sample output:

             total       used       free     shared    buffers     cached
Mem:          3952       3849        103          0       1917        574
-/+ buffers/cache:       1357       2595
Swap:          517        256        261

The total memory available to the OS is the total column in the Mem row: 3952 MB.

The top row used (3849) value will almost always nearly match the top row mem value (3952). Since Linux likes to use any spare memory to cache disk blocks (574).

The actual memory being used is in the -/+ buffers/cache row. The used value (1357) plus the free value (2595) will equal the total memory available to the OS (3952).

Determining swap usage is the same as before. The total swap available to the OS is in the total value (517), 256 MB is being used and 261 MB are still available.

Finding how much memory a process is using

This is especially helpful for tuning system daemons that can modify their memory usage, such as MySQL and Apache. We'll need to use ps as well as a few pipes to find the amounts we are looking for.

First, display just the processes for one program, and sort them by memory usage (rss) in order from lowest to highest thread. In this case, we'll use httpd:

ps a -ylC httpd --sort rss

Next, we only need the RSS column:

ps a -ylC httpd --sort rss | awk '{print $8'}

This still displays the memory usage for all the processes, and in the case of Apache, all the threads. We want to determine the maximum memory used out of all of them, so just return the last line:

ps a -ylC httpd --sort rss | awk '{print $8'} | tail -n 1

An example output would be 22596. You can verify this number by running htop, displaying only the processes for user apache, and sorting by resident memory:

htop -u apache --sort-key M_RESIDENT

Or, you can use top, though it is not sorted. Look at the RES column:

top -u apache -n 1

Divide that number by 1024 to determine the amount of memory used in MB.

echo 22596/1024 | bc
22

So, the thread using the most memory is taking 22 MB.