1. Exercises
Write a script that calculates the size of all processes in the Linux system and
2. Exercise Analysis 2.1. First question, where to collect data for a process
Use top or PS to get the memory usage size of each process. Once the size is obtained, they can be calculated by a loop.
2.2. PS Command Issues
It is not right to count the total amount of physical memory consumed by all processes by accumulating the RSS columns displayed by the PS aux command. Because, RSS (resident set size) represents the size of the resident memory, but because the memory is shared between different processes, the method of accumulating all the process RSS is to compute the shared memory repeatedly, resulting in a large result.
2.3. How to get the correct use of memory
The correct method is to accumulate Pss in the/proc/[0-9]*/smaps. /proc/<pid>/smaps contains statistical values for each memory map of the process, as detailed in the man page of the proc (5). PSS (proportional Set Size) evenly shares the RSS for shared memory, for example, a piece of 100MB of memory is shared by 10 processes, so each process is spread to 10MB. In this way, the cumulative PSS does not cause shared memory to be repeated.
3. Exercise Answer
grep Pss /proc/[0-9]*/smaps | awk ‘{sum+=$2};END{print sum}‘69275
Analysis
- The grep command iterates through the files in the directory and fetches the lines that match the matching characters;
- The awk command traverses the results of the grep output, and the statistics process uses the and of the memory.
- In the/proc directory, there are a lot of process-related data that readers can study on their own.
It is important to note that the memory consumed by all processes is not equal to the "used memory" displayed by the free command, because "used memory" contains not only the RAM occupied by the process, but also the Cache/buffer and kernel dynamically allocated memory, and so on.
Daily Shell Exercises (03)