Differences

This shows you the differences between two versions of the page.

Link to this comparison view

linux_memory_and_processes [2012/02/08 13:31]
linux_memory_and_processes [2012/02/08 13:31] (current)
Line 1: Line 1:
 +====== Linux Memory and Processes ======
 +
 +  * [[Apache Tuning]]
 +  * [[htop]]
 +
 +  * [[http://​rimuhosting.com/​howto/​memory.jsp|Troubleshooting memory usage]]
 +
 +Use ''​free''​ to determine how much memory is being used, and how much is available.
 +
 +Display memory usage in MB:
 +
 +<​code>​
 +free -m
 +</​code>​
 +
 +Sample output:
 +
 +<​code>​
 +             ​total ​      ​used ​      ​free ​    ​shared ​   buffers ​    ​cached
 +Mem:          3952       ​3849 ​       103          0       ​1917 ​       574
 +-/+ buffers/​cache: ​      ​1357 ​      2595
 +Swap:          517        256        261
 +</​code>​
 +
 +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:
 +
 +<​code>​
 +ps a -ylC httpd --sort rss
 +</​code>​
 +
 +Next, we only need the RSS column:
 +
 +<​code>​
 +ps a -ylC httpd --sort rss | awk '​{print $8'}
 +</​code>​
 +
 +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:
 +
 +<​code>​
 +ps a -ylC httpd --sort rss | awk '​{print $8'} | tail -n 1
 +</​code>​
 +
 +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:
 +
 +<​code>​
 +htop -u apache --sort-key M_RESIDENT
 +</​code>​
 +
 +Or, you can use top, though it is not sorted. ​ Look at the RES column:
 +
 +<​code>​
 +top -u apache -n 1
 +</​code>​
 +
 +Divide that number by 1024 to determine the amount of memory used in MB.
 +
 +<​code>​
 +echo 22596/1024 | bc
 +22
 +</​code>​
 +
 +So, the thread using the most memory is taking 22 MB.
 +
 +
 +