- Работа с процессами в Linux
- Список процессов
- Ключи
- Примеры
- Убить процесс
- Подробная информация о процессе
- Потребление ресурсов процессами
- How to List Running Processes in Linux
- Processes in Linux
- List Running Processes in Linux
- List Running Processes in Linux by Using the ps Command
- List Running Processes in Linux by Using the top Command
- List Running Processes in Linux by Using the htop Command
- List Running Processes in Linux by Using the atop Command
- Find Process IDs Using the pgrep Command
Работа с процессами в Linux
Обновлено: 29.03.2023 Опубликовано: 09.11.2017
Список процессов
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
root 661 0.0 0.0 4072 8 tty1 Ss+ Jul03 0:00 /sbin/mingetty
root 662 0.0 0.0 4072 8 tty2 Ss+ Jul03 0:00 /sbin/mingetty
root 16355 0.0 0.0 171636 3308 pts/0 S 15:46 0:00 sudo su
root 16366 0.0 0.0 140896 1556 pts/0 S 15:46 0:00 su
root 16368 0.0 0.0 108316 1944 pts/0 S 15:46 0:00 bash
root 18830 0.0 0.0 110244 1172 pts/0 R+ 16:20 0:00 ps u
- USER — учетная запись пользователя, от которой запущен процесс.
- PID — идентификатор процесса.
- %CPU — потребление процессорного времени в процентном эквиваленте.
- %MEM — использование памяти в процентах.
- VSZ — Virtual Set Size. Виртуальный размер процесса (в килобайтах).
- RSS — Resident Set Size. Размер резидентного набора (количество 1K-страниц в памяти).
- TTY — терминал, из под которого был запущен процесс.
- STAT — текущее состояние процесса. Могут принимать значения:
- R — выполнимый процесс;
- S — спящий;
- D — в состоянии подкачки на диске;
- T — остановлен;
- Z — зомби.
- W — не имеет резидентных страниц;
- < —высоко-приоритетный;
- N — низко-приоритетный;
- L — имеет страницы, заблокированные в памяти.
- START — дата запуска процесса.
- TIME — время запуска процесса.
- COMMAND — команда, запустившая процесс.
Ключи
Ключ | Описание |
---|---|
-A | Все процессы. |
-a | Запущенные в текущем терминале, кроме главных системных. |
-d | Все, кроме главных системных процессов сеанса. |
-e | Все процессы. |
f | Показать дерево процессов с родителями. |
T | Все на конкретном терминале. |
a | Все, связанные с текущим терминалом и терминалами других пользователей. |
r | Список только работающих процессов. |
x | Отсоединённые от терминала. |
u | Показать пользователей, запустивших процесс. |
Примеры
Поиск процесса с помощью grep:
Убить процесс
Останавливаем процесс по его PID:
Если процесс не завершается, убиваем его принудительно:
Остановить все процессы с именем nginx:
Как и в случае с kill, можно это сделать принудительно:
Можно остановить все процессы конкретного пользователя:
Ищем процесс по имени, извлекаем его PID и завершаем его:
kill `ps aux | grep ‘apache’ | awk »`
* обратите внимание, что запрос может вывести несколько процессов, которые будут попадать под критерии поиска — в таком случае, они будут завершены все.
Подробная информация о процессе
Для каждого процесса создается каталог по пути /proc/ , в котором создаются папки и файлы с описанием процесса.
Примеры использования /proc/
Адрес в ячейках оперативной памяти, которые занял процесс:
Команда, которой был запущен процесс:
Символьная ссылка на рабочий каталог процесса:
Символьная ссылка на исполняемый файл, запустивший процесс:
Увидеть ссылки на дескрипторы открытых файлов, которые затрагивает процесс:
Подробное описание на сайте man7.org.
Потребление ресурсов процессами
Для просмотра статистики потребления ресурсов используем утилиту top:
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
21059 root 20 0 157884 2280 1496 R 18,8 0,1 0:00.03 top
1 root 20 0 190996 2964 1652 S 0,0 0,1 6:49.99 systemd
2 root 20 0 0 0 0 S 0,0 0,0 0:01.78 kthreadd
3 root 20 0 0 0 0 S 0,0 0,0 0:24.75 ksoftirqd/0
5 root 0 -20 0 0 0 S 0,0 0,0 0:00.00 kworker/0:0H
- PID — идентификатор процесса.
- USER — имя учетной записи, от которой запущен процесс.
- PR — приоритет процесса.
- NI — приоритет, выставленной командой nice.
- VIRT — объем виртуальной памяти, потребляемый процессом.
- RES — объем используемой оперативной памяти.
- SHR — количество разделяемой памяти, которое используется процессом.
- S — состояние процесса.
- %CPU — процент использования процессорного времени.
- %MEM — потребление оперативной памяти в процентах.
- TIME — использование процессорного времени в секундах.
- COMMAND — команда, которая запустила процесс.
How to List Running Processes in Linux
Each application you use or a command you run on your Linux system creates a process or task. As a system administrator, you will need to manage processes to ensure optimal system performance.
In this tutorial, we will cover different Linux commands you can use to list and manage currently running processes.
- A system running Linux
- An account with root or sudo privileges
- Access to the terminal window/command line
Processes in Linux
Processes in Linux start every time you launch an application or run a command. While each command creates one process, applications create and run multiple processes for different tasks.
By default, each new process starts as a foreground process. This means it must finish before a new process can begin. Running processes in the background allows you to perform other tasks at the same time.
Note: Learn more about terminating Linux processes in our guide to killing processes in Linux.
List Running Processes in Linux
To list currently running processes, use the ps , top , htop , and atop Linux commands. You can also combine the ps command with the pgrep command to identify individual processes.
List Running Processes in Linux by Using the ps Command
The ps Linux command creates a snapshot of currently running processes. Unlike the other commands on this list, ps presents the output as a static list, not updated in real time.
The ps command uses the following syntax:
Frequently used ps command options include:
- a : List all ruining processes for all users.
- -A, -e : List all processes on the system.
- -a : List all processes except session leaders (instances where the process ID is the same as the session ID) and processes not associated with a terminal.
- -d : List all processes except session leaders.
- —deselect, -N : List all processes except those that fulfill a user-defined condition.
- f : Displays process hierarchy as ASCII art.
- -j : Displays output in the jobs format.
- T : List all processes associated with this terminal.
- r : Only list running processes.
- u : Expand the output to include additional information, for example, CPU and memory usage.
- -u : Define a user whose processes you want to list.
- x : Include processes without a TTY.
Note: Check the complete list of ps command options by using man ps .
Running the ps command without any options produces an output similar to:
The default output includes the following categories:
- PID: Process identification number.
- TTY: The type of terminal the process is running on.
- TIME: Total amount of CPU usage.
- CMD: The name of the command that started the process.
Using the combination of a , u , and x options results in a more detailed output:
The new categories of the expanded output include:
- USER: The name of the user running the process.
- %CPU: The CPU usage percentage.
- %MEM: The memory usage percentage.
- VSZ: Total virtual memory used by the process, in kilobytes.
- RSS: Resident set size, the portion of RAM occupied by the process.
- STAT: The current process state.
- START: The time the process was started.
To display the running processes in a hierarchical view, enter:
Note: When using more than one ps command option containing a dash symbol («—«), you only need to use one dash symbol before listing the options. For instance, to use the ps command with the -e and -f options, type ps -ef .
Filter the list of processes by user with:
ps -U [real user ID or name] -u [effective user ID or name] u
For example, showing a list of processes started by the user called phoenixnap:
ps -U phoenixnap -u phoenixnap u
List Running Processes in Linux by Using the top Command
The top command displays the list of running processes in the order of decreasing CPU usage. This means that the most resource-heavy processes appear at the top of the list:
The output of the top command updates in real time, with the three-second default refresh rate. The top command output contains the following categories:
- PID: Process identification number.
- USER: The name of the user running the process.
- PR: The scheduling priority for the process.
- NI: The nice value of the process, with negative numbers indicating higher priority.
- VIRT: The virtual memory amount used by the process.
- RES: The resident (physical) memory amount used by the process.
- SHR: The total shared memory used by the process.
- S: The status of the process — R (running) or S (sleeping).
- %CPU: The percentage of CPU usage.
- %MEM: The memory usage percentage.
- TIME+: Total CPU usage amount.
- COMMAND: The name of the command that started the process.
While the top command is running, use the following options to interact with it or change the output format:
- c: Display the absolute process path.
- d: Change the output refresh rate to a user-defined value (in seconds).
- h: Display the help window.
- k: Kill a process by providing the PID.
- M: Sort the list by memory usage.
- N: Sort the list by PID.
- r: Change the nice value (priority) of a process by providing the PID.
- z: Change the output color to highlight running processes.
- q: Quit the command interface.
Note: Options for interacting with the top command are case-sensitive. Make sure you turn the Caps Lock off first.
List Running Processes in Linux by Using the htop Command
The htop command offers the same output as the top command but in an easier-to-understand and user-friendly way.
Since most Linux distributions don’t include this command, install it with:
Using the htop command provides the following output:
Use the following keys to interact with the htop command:
- Directional keys: Scroll the process list vertically and horizontally.
- F1: Open the help window.
- F2: Open the htop command setup.
- F3: Search for a process by typing the name.
- F4: Filter the process list by name.
- F5: Switch between showing the process hierarchy as a sorted list or a tree.
- F6: Sort processes by columns.
- F7: Decrease the nice value (increase priority) of a process.
- F8: Increase the nice value (decrease priority) of a process.
- F9: Kill the selected process.
- F10: Exit the command interface.
List Running Processes in Linux by Using the atop Command
The atop command provides a more comprehensive overview of the running processes compared to the top command. Start by installing the atop command with:
The atop command creates an output similar to:
The heading section of the command output provides an overview of system resources, including process and performance-related statistics and memory, disk, and network usage.
The lower section lists currently running processes and contains the following categories:
- PID: Process identification number.
- SYSCPU: The CPU usage by the process while system handling.
- USRCPU: The CPU usage by the process while running in user mode.
- VGROW: The amount of virtual memory the process has occupied since the last output update.
- RGROW: The amount of physical memory the process has occupied since the last output update.
- RUID: The real user ID of the user that started the process.
- ST: The current process status.
- EXC: The exit code after the process terminates.
- THR: The number of threads the process is using.
- S: The current status of the primary thread of the process.
- CPUNR: The number of CPUs used by the process.
- CPU: The CPU percentage used by the process.
- CMD: The name of the command that started the process.
Using the atop command with the following options changes the output format:
- -a : Show active processes only.
- -c : Show command line per process.
- -d : Show disk information.
- -l : Show total values as average-per-second.
- -m : Show memory information.
- -n : Show network information.
- -s : Show process scheduling information.
- -v : Show the verbose output.
- -y : Show individual threads.
Use the following flags to interact with the atop command:
- a: Sort by most active resources.
- c: Sort by CPU consumption.
- d: Sort by disk activity.
- m: Sort by memory usage.
- n: Sort by network activity.
Find Process IDs Using the pgrep Command
Using the pgrep command allows you to search for a specific process. The pgrep command uses the following syntax:
For instance, use the following command to search for the firefox process:
The command output lists the PID of the process:
Using this PID with the ps command allows you to get more information on the process. In this example, using the PID 1439 provides information on the firefox process:
After reading this tutorial, you should be able to use the ps , top , htop , and atop commands to list and manage running processes in Linux.
Use the available command options to customize the output and command behavior.