10 Essential Linux Commands to Rescue Your Server When Memory is Full!

When the server’s memory is full, the most immediate feeling is that website access becomes exceptionally slow. Imagine a user eagerly clicking into a website, only to see the frustrating loading icon for an extended period; every second of waiting is wearing down the user’s patience. For e-commerce websites, this could lead to users abandoning their purchases, directly impacting sales; for news websites, users may quickly turn to competing platforms, resulting in user loss.

Worse still, a full memory can cause the server to crash, bringing the entire system to a standstill. For financial institutions, this could prevent transactions from occurring, resulting in significant economic losses; for healthcare information management systems, a server crash could affect patient diagnosis and treatment, even endangering lives. Thus, a full server memory is not a trivial issue; timely resolution is urgent, and proficient use of Linux commands is one effective way to address this dilemma.

Understanding Memory Usage

Before addressing the issue of full server memory, we first need to clearly understand the current memory usage of the server; only then can we take targeted measures. In Linux systems, there are several very practical commands that can help us achieve this goal.

free Command: Check Memory Status

The free command is a commonly used command in Linux systems for checking memory usage; it can display the usage of the system’s physical memory, swap space, and kernel buffers. Its basic usage is very simple; just type the “free” command in the terminal, and it will display memory information in KB by default. However, to make the output more readable, we usually add the “-h” option to display in human-readable formats like GB/MB/KB. For example:

free -h

After executing the above command, you will get an output similar to the following:

             total        used        free      shared  buff/cache   available

Mem:           7.7G        3.1G        1.9G        200M        2.7G        4.3G

Swap:          2.0G        500M        1.5G

Now, let’s explain the meaning of each field in detail:

  • total: Represents the total amount of memory; here, the “total” in the “Mem” row is the total physical memory, and the “total” in the “Swap” row is the total swap space. In the above example, the total physical memory is 7.7G, and the total swap space is 2.0G.
  • used: The amount of memory that is currently used. Note that the used memory here includes memory occupied by buffers and caches, not just the memory actually occupied by applications. In this example, 3.1G of physical memory is used.
  • free: Refers to the memory that is completely unused. However, it does not include reclaimable buffers and caches. In the example, the currently completely unused physical memory is 1.9G.
  • shared: Memory shared by temporary file systems (like tmpfs) or between processes. As shown in the output, “shared” is 200M, indicating that this portion of memory is shared by multiple processes.
  • buff/cache: Buffers are kernel buffers (Block Buffer) used to temporarily store disk block data, speeding up disk I/O; cache is page cache (Page Cache) and Slab memory (like directory entry cache), speeding up file access. This portion of memory can be quickly released for program use; in the above example, “buff/cache” is 2.7G.
  • available: Estimated available memory, reflecting how much memory the system can still allocate to new programs without swapping. This value takes into account both free memory and reclaimable buff/cache, providing a better representation of actual available memory than the free column. In this example, “available” is 4.3G.

Through the free command, we can quickly understand the overall memory usage status of the system, including the usage of physical memory and swap space, providing foundational data for subsequent analysis and resolution of memory issues.

top Command: Real-time Memory Monitoring

The top command is a powerful real-time system monitoring tool that not only allows you to view the running status of system processes in real-time but also monitors memory usage status in real-time. Type the “top” command in the terminal to start this tool.

After starting the top command, you will enter an interactive interface that displays relevant information about each process in the system. By default, the process list is sorted by CPU usage. However, when we are more concerned about memory usage, we can press the “M” key (uppercase), at which point the top command will immediately sort the processes by memory usage (MEM%), allowing the processes with the highest memory usage to be at the top of the list, making it easier for us to quickly identify memory hogs. For example, when the server memory is abnormal, this method can quickly locate which process is consuming a large amount of memory resources.

In the output interface of the top command, the information related to memory mainly includes the following columns:

  • VIRT: The amount of virtual memory used, including all memory used by the process, regardless of whether it has been swapped out. It includes physical memory, swap, and shared library memory.
  • RES: The amount of resident memory used, indicating the amount of memory currently being used by the process that has not been swapped out; this is the actual physical memory occupied by the process.
  • SHR: The amount of shared memory, referring to the memory shared by this process with other processes, such as memory occupied by shared libraries; this portion of memory is not fully counted in the process’s exclusive memory.
  • %MEM: The percentage of memory usage, indicating the percentage of total system memory used by this process; this metric provides an intuitive understanding of each process’s memory resource usage ratio.

In addition to sorting by memory usage, the top command also provides many useful shortcuts that help us view and manage processes more efficiently. For example, pressing the “P” key sorts by CPU usage; pressing the “T” key sorts by accumulated CPU time; pressing the “k” key kills a specified process (use with caution, input the process ID and signal, the default signal is SIGTERM); pressing the “r” key resets the nice value of a process, adjusting the process priority (the nice value ranges from -20 to 19, with lower values indicating higher priority); pressing the “u” key filters processes by user, showing all processes for a specified user.

The top command acts like a dashboard for real-time monitoring of system resources, allowing us to dynamically observe the memory and other system resource usage of each process, providing strong support for timely detection and resolution of memory-related issues. Whether troubleshooting high memory usage processes or conducting comprehensive monitoring and analysis of system performance, the top command is an indispensable tool for Linux system administrators and developers.

Releasing Cached Memory

In Linux systems, cached memory (buffers and cache) helps improve system I/O performance, but in memory-constrained situations, releasing cached memory can free up more available memory for other processes. Below are two methods to release cached memory.

sync and echo to Release Cache

The sync command in Linux is a key tool for ensuring data integrity; its core function is to force the unsaved data in the memory buffer (cache) to be written to the physical disk, preventing data loss due to system crashes, power outages, or accidental operations.

To improve I/O performance, Linux temporarily stores write operations in the memory buffer (called “dirty pages”) rather than writing them directly to the disk. The sync command forces these cached data to be flushed to the disk by calling the kernel’s sync() system function, ensuring that modified file contents and metadata (such as inode and directory structure) are persistently stored. It is crucial to execute the sync command before performing cache memory release operations, as it ensures that the data in memory has been safely written to the disk, avoiding data loss during cache release.

The operation to release cached memory is achieved by writing specific parameters to the /proc/sys/vm/drop_caches file using the echo command. The /proc/sys/vm/drop_caches is a kernel interface that allows user-space programs to request the cleaning of certain types of caches. Specifically, writing different values to this file represents different cache cleaning operations:

  • echo 1 > /proc/sys/vm/drop_caches: Clears only the page cache (Page Cache), which is the file system cache that stores data read from disk.
  • echo 2 > /proc/sys/vm/drop_caches: Clears only the directory entry cache (dentries cache) and inode cache; the directory entry cache is used to speed up file path resolution, and the inode cache stores file metadata information.
  • echo 3 > /proc/sys/vm/drop_caches: Simultaneously releases all caches, including page cache, directory entry cache, and inode cache.

For example, to release all caches, you can use the following commands (requiring root privileges, hence using sudo):

sudo sync

sudo echo 3 > /proc/sys/vm/drop_caches

It is important to note that executing this operation will immediately remove these cached contents from memory, which may lead to a temporary performance drop, as subsequent file accesses will need to reload data from the disk. Therefore, this operation is usually only recommended in specific situations (such as testing memory usage, diagnosing memory-related issues, or when memory pressure is high and it is certain that cached content is no longer needed).

Comparing Memory Changes Before and After Release

To visually see the effect of releasing cached memory, we can use the free -h command to check memory status before and after the release operation.

Assuming that before executing the cache release command, using the free -h command yields the following output:

             total        used        free      shared  buff/cache   available

Mem:           7.7G        3.1G        1.9G        200M        2.7G        4.3G

Swap:          2.0G        500M        1.5G

At this point, we can see that buff/cache occupies 2.7G of memory. Next, execute the cache release command:

sudo sync

sudo echo 3 > /proc/sys/vm/drop_caches

Use the free -h command again to check memory, yielding the following result:

             total        used        free      shared  buff/cache   available

Mem:           7.7G        3.1G        3.5G        200M        1.1G        4.3G

Swap:          2.0G        500M        1.5G

Comparing the two, we find that after releasing the cache, free memory increased from 1.9G to 3.5G, and buff/cache memory decreased from 2.7G to 1.1G. This indicates that the cache release operation successfully freed cached memory, increasing the system’s available memory, clearly demonstrating the impact of releasing cached memory on the system’s memory status. Through this comparison, we can better understand the actual effect and role of the cache release operation in solving server memory pressure issues.

Investigating Memory-Hogging Processes

When the server memory is full, in addition to understanding the overall memory usage and releasing cached memory, we also need to further investigate which processes are consuming a large amount of memory to take targeted measures. In Linux systems, there are several commands that can help us accomplish this task.

ps Command: Locate Memory-Hogging Processes

The ps command is a tool in Linux systems used to report the current status of system processes; it is powerful and can provide rich process information. By combining specific options, we can use the ps command to find processes that occupy a large amount of memory.

To list process information sorted in descending order by memory usage and view the top 10 memory-consuming processes, you can use the following command:

ps aux --sort=-%mem | head -10

In this command:

  • ps aux: “ps” is the command itself, and “aux” is the option combination. “a” means to display all programs executed under all terminals, except for the stage job leader; “u” displays the program status in a user-oriented format; “x” means to display all programs without distinguishing by terminal. This way, we can obtain detailed information about all processes in the system.
  • –sort=-%mem: Indicates sorting by memory usage percentage (% MEM) in descending order; the “-” sign indicates descending order, and removing the “-” sign would sort in ascending order.
  • | head -10: The “|” is a pipe symbol used to pass the output of the ps command as input to the next command; “head -10” means to display only the first 10 lines of results, allowing us to quickly locate the top 10 memory-consuming processes.

After executing the above command, you will get an output similar to the following:

USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND

root     23456  0.1  5.2 123456  52428 ?        Ss   08:00   0:05 /usr/local/bin/application

user1    12345  0.0  3.8  87654  38912 pts/0    S+   08:10   0:01 /home/user1/script.sh

root      5678  0.2  2.5  56789  25600 ?        S    07:50   0:03 /usr/sbin/service_name

The meanings of the fields in the output are as follows:

  • USER: The user who started the process. In the above example, “root” indicates the process was started by the root user, and “user1” indicates it was started by user1.
  • PID: The process ID, which is the unique identifier for each process in the system. The PID can be used to perform various operations on the process, such as terminating it (using the kill command).
  • %CPU: The percentage of CPU used by the process, indicating the proportion of CPU resources used by this process over a period of time. Here, the % CPU for the process “23456” is 0.1, indicating it occupies 0.1% of CPU resources.
  • %MEM: The percentage of memory used by the process, which is the proportion of total system memory used by this process; this is the key field we focus on to assess the memory usage of processes. For example, the % MEM for process “23456” is 5.2, indicating it occupies 5.2% of system memory.
  • VSZ: The virtual memory usage (Virtual Memory Size), measured in KB. It indicates the total amount of virtual memory requested by the process, including the memory occupied by the process’s code segment, data segment, heap, shared libraries, and mapped files. This value can be large because it includes all virtual address space accessible to the process, even if some memory may not have been physically allocated yet.
  • RSS: The resident set size (Resident Set Size), measured in KB. It indicates the amount of physical memory currently being used by the process that has not been swapped out, which is the actual physical memory occupied by the process. For example, the RSS for process “23456” is 52428KB, meaning this process actually occupies 52428KB of physical memory.
  • TTY: Indicates the terminal device on which the process is running. “?” indicates that the process was not started by a terminal, while “pts/0” indicates it is running on pseudo-terminal 0.
  • STAT: The process status; common statuses include “R” (running), “S” (sleeping), “D” (uninterruptible sleep), “T” (stopped), “Z” (zombie process), etc. Here, the status of process “23456” is “Ss”, where the first “S” indicates a sleeping state, and “s” indicates that this process is a session leader.
  • START: The time when the process started. For example, “08:00” indicates that this process started at 8 o’clock.
  • TIME: The total CPU time used by the process. “0:05” indicates that this process has used 5 seconds of CPU time.
  • COMMAND: The command that started the process. This field indicates the specific program or script corresponding to the process, such as “/usr/local/bin/application”, indicating that this is an application named “application” located in the “/usr/local/bin” directory.

Through this usage of the ps command, we can quickly obtain information about processes with high memory usage in the system, providing important evidence for subsequent analysis and handling of memory issues.

pmap Command: Analyze Process Memory Mapping

The pmap command is a tool in Linux systems used to display the memory mapping information of a specified process; it can show detailed information about the memory allocation of the process, helping us understand how the process uses memory.

When using the pmap command, you need to specify the process ID (PID) to analyze. For example, to view the memory mapping of the process with PID 12345, you can use the following command:

pmap 12345

If you want to obtain more detailed memory mapping information, including the starting address of memory areas, size, actual resident memory (RSS), dirty page size, and access permissions, you can use the “-x” option to display in extended format:

pmap -x 12345

After executing the “pmap -x 12345” command, you will get an output similar to the following:

12345:   /usr/sbin/sshd

Address           Kbytes     RSS   Dirty Mode   Mapping

0000555555554000   4096K    1024K     512K r-x--  /usr/sbin/sshd

0000555555555000     20K       4K       4K rw---  /usr/sbin/sshd

00007ffff7a0d000  16384K    2048K    1024K r-x--  /lib/x86_64-linux-gnu/libc-2.31.so

00007ffff7b0d000   4096K       0K       0K ---p   /lib/x86_64-linux-gnu/libc-2.31.so

00007ffff7c0d000     12K       4K       4K r--p   /lib/x86_64-linux-gnu/libc-2.31.so

00007ffff7c0e000      4K       4K       4K rw-p   /lib/x86_64-linux-gnu/libc-2.31.so

00007ffff7c0f000    132K     128K     128K rw---  [ heap ]

00007ffff7c31000      4K       4K       4K r-x--  [ anon ]

00007ffff7c32000      4K       4K       4K rw---  [ stack ]

Now, let’s explain the meanings of each field in the output:

  • 12345: /usr/sbin/sshd: The first line shows the PID of the process and the path of the corresponding executable file; here, it indicates that the process with PID 12345 is the “sshd” (SSH daemon).
  • Address: The starting address of the memory area, used to identify the starting position of each memory segment in the process’s memory space, allowing us to determine the layout of the memory space. For example, “0000555555554000” is the starting address of the code segment of “sshd”.
  • Kbytes: The size of the memory area, measured in kilobytes (KB), indicating the total size allocated for that memory segment. The size of the memory segment “0000555555554000” is 4096KB.
  • RSS: The actual resident memory (Resident Set Size), which indicates the actual amount of memory occupied by this memory area in physical memory, reflecting the true physical memory size occupied by the process. In the above example, the RSS for the memory segment “0000555555554000” is 1024KB.
  • Dirty: The size of dirty pages, referring to the amount of memory that has been modified but not yet written back to disk. Dirty pages are pages in memory that have been modified but not yet synchronized to disk; understanding the size of dirty pages helps assess the usage of caches and buffers. The dirty size for the memory segment “0000555555554000” is 512KB.
  • Mode: The access permissions of the memory area; common permissions include “r-x–” (read and execute only), “rw—” (read and write), “—p” (no permissions), etc. Permissions determine how the process can operate on that memory area; for example, the permission for the memory segment “0000555555554000” is “r-x–“, indicating that this segment is readable and executable but not writable.
  • Mapping: The file path or mapping description corresponding to this memory area. If it is an executable file or shared library, its path will be displayed; if it is heap, stack, or other memory areas, it will show the corresponding description, such as “[heap]” indicating heap memory, and “[stack]” indicating stack memory. The Mapping field clearly indicates which files or memory areas are associated with each memory segment.

Through the output of the pmap command, we can comprehensively understand the memory usage of the process, including the allocation size of each memory segment, the actual amount of physical memory occupied, access permissions, and the mapping relationship with files. This is very helpful for troubleshooting memory leaks, analyzing shared library loading situations, and optimizing program performance. For example, if we find that a certain process’s heap memory keeps growing without being released, there may be a memory leak issue; or by analyzing the mapping of shared libraries, we can determine whether unnecessary shared libraries are loaded for optimization. In summary, the pmap command is a powerful tool for in-depth analysis of process memory usage.

Optimizing Memory Usage

Rational Use of Swap Space

In Linux systems, swap space is a virtual memory mechanism that allows the operating system to write some inactive memory pages to disk when physical memory is insufficient, thereby freeing physical memory for currently needed processes. When these swapped-out pages are needed again, they will be reloaded into memory. Swap space can be a dedicated disk partition or a regular file that is mounted for use as swap.

To check the usage of swap space, you can use the following commands:

  • free -h: As previously introduced, it displays the usage of the system’s physical memory, swap, and kernel buffers; in the output, you can find the total, used, and remaining space of swap. For example:
free -h
  • swapon –show: This command displays detailed information about currently enabled swap devices or files, including device or file path, type, size, used space, and priority. After executing the command, the output is similar to the following:
NAME      TYPE      SIZE  USED  PRIO

/swapfile file      2.0G  500M  -2
  • cat /proc/swaps: This command can also check the usage of the current system’s swap partitions or files, with output information similar to swapon –show. After executing, the output example is:
Filename                Type        Size    Used    Priority

/swapfile               file        2048000 512000  -2

If the server’s physical memory is insufficient and the swap space is also heavily used or nonexistent, then it is necessary to consider creating or adjusting the size of the swap space. Below is an example of creating a new swap file, detailing the steps:

  1. 1. Create a Swap File: You can use the fallocate command to create a file of a specified size as swap space, for example, creating a 4GB swap file:
sudo fallocate -l 4G /swapfile

Here, the “-l” option is used to specify the file size, set to 4G. If the system does not support the fallocate command, you can also use the dd command to create it, but the dd command is relatively slow:

sudo dd if=/dev/zero of=/swapfile bs=1M count=4096

Here, “if=/dev/zero” indicates reading data from the /dev/zero device (which is a special device that continuously returns a stream of zero-value bytes), “of=/swapfile” indicates writing data to the /swapfile file, “bs=1M” specifies the block size as 1MB, and “count=4096” indicates writing 4096 blocks, which equals 4GB in size.

2. Set File Permissions: Ensure that only the root user can read and write to this swap file to ensure system security.

sudo chmod 600 /swapfile
  1. 1. Format the Swap File: Format the created file as a swap file system.
sudo mkswap /swapfile
  1. 1. Enable the Swap File:
sudo swapon /swapfile
  1. 1. Set Automatic Mounting at Boot: To ensure that the swap file remains effective after the system restarts, it needs to be added to the /etc/fstab file. Use a text editor to open the /etc/fstab file (e.g., using sudo nano /etc/fstab), and add the following line at the end:
/swapfile none swap sw 0 0

Save and exit the editor.

If you need to adjust the size of existing swap space, such as expanding the swap file, you can first use the swapoff command to turn off the swap file, then adjust the file size as needed (e.g., using fallocate -l new_size /swapfile), reformat (mkswap /swapfile), and enable it (swapon /swapfile). Reducing the swap file size is similar, but you need to be cautious about data safety to ensure that important data is not lost.

Adjusting System Memory Parameters

In Linux systems, by modifying memory-related parameters in the /etc/sysctl.conf file, we can optimize memory usage and improve system performance. This file is the configuration file for system kernel parameters, and many kernel parameters can be set and adjusted here.

Among them, swappiness is an important memory parameter that controls the system’s tendency to swap memory data to swap space, with a range of 0 – 100. By default, the value of swappiness is usually 60, indicating that when memory is tight, the system has a 60% tendency to swap memory data to swap space. If you want the system to use swap space less and rely more on physical memory, you can lower the value of swappiness. For example, to set it to 10, you can achieve this through the following steps:

  1. 1. Temporary Modification: Use the sysctl command to temporarily modify the value of swappiness, which takes effect immediately but will revert to the default value after a system restart.
sudo sysctl vm.swappiness=10
  1. 1. Permanent Modification: Edit the /etc/sysctl.conf file, adding or modifying the vm.swappiness parameter. Use a text editor to open this file (e.g., sudo nano /etc/sysctl.conf), and add or modify the following line:
vm.swappiness=10

After saving and exiting the editor, execute the following command to make the configuration effective:

sudo sysctl -p

The “-p” option indicates loading system parameters from the configuration file, making the modified parameters effective during system operation. By lowering the value of swappiness, we can reduce the system’s reliance on swap space, improving system performance, especially when physical memory is relatively sufficient. However, if physical memory is indeed insufficient, excessively lowering swappiness may lead to frequent OOM (Out-Of-Memory) errors, so adjustments should be made based on actual conditions.

In addition to the swappiness parameter, there are other important memory-related parameters in the /etc/sysctl.conf file, such as vm.overcommit_memory, which controls the kernel’s memory allocation strategy:

  • vm.overcommit_memory=0: This is the default value, adopting a heuristic allocation strategy. The kernel will determine whether to allow memory allocation based on the system’s memory usage and some algorithms. In most cases, it can balance system performance and stability well. When memory allocation requests exceed the currently available memory, the kernel will evaluate based on certain rules; if it deems the risk low, it will allow allocation; otherwise, it will refuse.
  • vm.overcommit_memory=1: Indicates that allocation exceeding physical memory is always allowed. In this mode, the kernel will not impose strict limits on memory allocation, even if the system’s physical memory and swap space are insufficient; it will try to satisfy memory allocation requests. This setting may lead to severe performance issues or even crashes when memory is insufficient, but in certain special scenarios, such as running applications with unpredictable memory needs and wanting to avoid program interruptions due to memory allocation failures, this setting may be used.
  • vm.overcommit_memory=2: This is strict mode, which does not allow memory allocation exceeding the total of “swap + physical memory.” It strictly limits memory allocation, ensuring that the system does not fall into a dangerous state due to excessive memory allocation, suitable for scenarios with high stability requirements.

Similarly, modifying the vm.overcommit_memory parameter can be done through temporary modification (sysctl -w vm.overcommit_memory=X) and permanent modification (editing the /etc/sysctl.conf file and executing sysctl -p). In practical applications, adjustments to these memory parameters should be made cautiously based on the server’s load conditions, application requirements, and memory configuration to optimize memory usage and enhance system performance and stability.

Monitoring and Preventing Memory Issues

sar Command: Long-term Memory Monitoring

The sar (System Activity Reporter) command is a powerful system performance analysis tool in Linux systems that can collect and analyze various performance data over the long term, including memory usage, providing system administrators with a comprehensive understanding of the system’s operating status. The data collection of the sar command is implemented through a background process called sadc (System Activity Data Collector). The sadc process periodically collects system performance data at set intervals and writes this data to system log files, which are by default located in the /var/log/sa/ directory, with log file naming format saDD, where DD represents the date.

The basic syntax of the sar command is:

sar [options] [-o filename] interval [count]

Where:

  • options: Optional parameters used to specify the type of data to collect and display, such as “-u” for CPU usage and “-r” for memory usage.
  • -o filename: Indicates that the command results should be stored in a specified file in binary format for later analysis.
  • interval: The sampling interval time, in seconds, which must be set manually.
  • count: The number of samples, which is optional, with a default value of 1.

To use the sar command to periodically collect memory data, for example, collecting memory usage every 10 minutes and saving the data to /tmp/memory_data, you can use the following command:

sar -r 600 -o /tmp/memory_data

Here, the “-r” option is used to collect memory usage data, and “600” indicates a sampling interval of 600 seconds (i.e., 10 minutes). This command will run continuously, collecting memory data at 10-minute intervals and saving it to the /tmp/memory_data file.

If you want to view previously saved memory data reports, you can use the “-f” option to read data from the specified file and generate reports. For example, to view the memory data report from the recently saved /tmp/memory_data file:

sar -f /tmp/memory_data

Executing the above command will yield output similar to the following:

Linux 5.4.0-106-generic (server.example.com)  01/01/2024  _x86_64_  (4 CPU)

10:00:00 AM kbmemfree kbmemused  %memused kbbuffers  kbcached  kbcommit   %commit  kbactive   kbinact

10:10:00 AM   1024000   67108864   98.51      51200   2097152  70778880   99.99  32768000  20971520

10:20:00 AM   819200    67300352   98.75      51200   2199040  70878208   99.99  33554432  21990400

The meanings of the fields in the output are as follows:

  • kbmemfree: The size of free memory, in KB.
  • kbmemused: The size of used memory, in KB.
  • %memused: Memory usage rate, the percentage of used memory relative to total memory.
  • kbbuffers: The size of buffer memory, in KB.
  • kbcached: The size of cached memory, in KB.
  • kbcommit: The size of committed memory, in KB, including the total amount of memory used in physical memory and swap.
  • %commit: The percentage of committed memory relative to total memory (physical memory + swap).
  • kbactive: The size of active memory, in KB, referring to memory that has been accessed recently.
  • kbinact: The size of inactive memory, in KB, referring to memory that has not been accessed for a long time.

By using the sar command for long-term monitoring of memory usage, we can obtain historical data on system memory usage, analyze memory usage trends, and promptly detect abnormal memory usage situations, providing strong support for system performance optimization and memory issue troubleshooting.

Automated Memory Monitoring Script

In addition to using the sar command for long-term memory monitoring, we can also write simple shell scripts to periodically check memory usage and send email or SMS alerts when memory usage exceeds a set threshold, thus achieving early warning of memory issues.

Below is a simple shell script example that checks memory usage and sends an email alert when it exceeds 80%:

#!/bin/bash

# Define email sending related information

EMAIL="[email protected]"

SMTP_SERVER="smtp.example.com"

SMTP_PORT=587

SMTP_USER="[email protected]"

SMTP_PASSWORD="your_email_password"

# Get memory usage

mem_usage=\

Leave a Comment