Linux посмотреть текущие процессы

Работа с процессами в 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 — текущее состояние процесса. Могут принимать значения:
    1. R — выполнимый процесс;
    2. S — спящий;
    3. D — в состоянии подкачки на диске;
    4. T — остановлен;
    5. Z — зомби.
    6. W — не имеет резидентных страниц;
    7. < —высоко-приоритетный;
    8. N — низко-приоритетный;
    9. 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 »`

Читайте также:  Samba linux file sharing

* обратите внимание, что запрос может вывести несколько процессов, которые будут попадать под критерии поиска — в таком случае, они будут завершены все.

Подробная информация о процессе

Для каждого процесса создается каталог по пути /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 — команда, которая запустила процесс.

Источник

Linux List Processes – How to Check Running Processes

Bolaji Ayodeji

Bolaji Ayodeji

Linux List Processes – How to Check Running Processes

Every day, developers use various applications and run commands in the terminal. These applications can include a browser, code editor, terminal, video conferencing app, or music player.

For each of these software applications that you open or commands you run, it creates a process or task.

One beautiful feature of the Linux operating system and of modern computers in general is that they provide support for multitasking. So multiple programs can run at the same time.

Have you ever wondered how you can check all the programs running on your machine? Then this article is for you, as I’ll show you how to list, manage, and kill all the running processes on your Linux machine.

Prerequisites

  • A Linux distro installed.
  • Basic knowledge of navigating around the command-line.
  • A smile on your face 🙂

A Quick Introduction to Linux Processes

A process is an instance of a running computer program that you can find in a software application or command.

Читайте также:  Canon lbp 810 driver linux

For example, if you open your Visual Studio Code editor, that creates a process which will only stop (or die) once you terminate or close the Visual Studio Code application.

Likewise, when you run a command in the terminal (like curl ifconfig.me ), it creates a process that will only stop when the command finishes executing or is terminated.

How to List Running Processes in Linux using the ps Command

You can list running processes using the ps command (ps means process status). The ps command displays your currently running processes in real-time.

To test this, just open your terminal and run the ps command like so:

Screenshot-2021-06-28-at-3.25.33-PM

This will display the process for the current shell with four columns:

  • PID returns the unique process ID
  • TTY returns the terminal type you’re logged into
  • TIME returns the total amount of CPU usage
  • CMD returns the name of the command that launched the process.

You can choose to display a certain set of processes by using any combination of options (like -A -a , -C , -c , -d , -E , -e , -u , -X , -x , and others).

If you specify more than one of these options, then all processes which are matched by at least one of the given options will be displayed.

Screenshot-2021-06-28-at-3.55.10-PM

Type man ps in your terminal to read the manual for the ps command, which has a complete reference for all options and their uses.

To display all running processes for all users on your machine, including their usernames, and to show processes not attached to your terminal, you can use the command below:

Here’s a breakdown of the command:

Screenshot-2021-06-28-at-4.39.05-PM

  • ps : is the process status command.
  • a : displays information about other users’ processes as well as your own.
  • u : displays the processes belonging to the specified usernames.
  • x : includes processes that do not have a controlling terminal.

This will display the process for the current shell with eleven columns:

  • USER returns the username of the user running the process
  • PID returns the unique process ID
  • %CPU returns the percentage of CPU usage
  • %MEM returns the percentage memory usage
  • VSV returns the virtual size in Kbytes
  • RSS returns the resident set size
  • TT returns the control terminal name
  • STAT returns the symbolic process state
  • STARTED returns the time started
  • CMD returns the command that launched the process.
Читайте также:  Linux folder list file

How to List Running Processes in Linux using the top and htop Commands

You can also use the top task manager command in Linux to see a real-time sorted list of top processes that use the most memory or CPU.

Type top in your terminal and you’ll get a result like the one you see in the screenshot below:

Screenshot-2021-06-28-at-4.27.28-PM

An alternative to top is htop which provides an interactive system-monitor to view and manage processes. It also displays a real-time sorted list of processes based on their CPU usage, and you can easily search, filter, and kill running processes.

htop is not installed on Linux by default, so you need to install it using the command below or download the binaries for your preferred Linux distro.

sudo apt update && sudo apt install htop

Just type htop in your terminal and you’ll get a result like the one you see in the screenshot below:

Screenshot-2021-06-29-at-4.49.09-AM

How to Kill Running Processes in Linux

Killing a process means that you terminate a running application or command. You can kill a process by running the kill command with the process ID or the pkill command with the process name like so:

To find the process ID of a running process, you can use the pgrep command followed by the name of the process like so:

To kill the iTerm2 process in the screenshot above, we will use any of the commands below. This will automatically terminate and close the iTerm2 process (application).

Conclusion

When you list running processes, it is usually a long and clustered list. You can pipe it through less to display the command output one page at a time in your terminal like so:

or display only a specific process that matches a particular name like so:

I hope that you now understand what Linux processes are and how to manage them using the ps , top , and htop commands.

Make sure to check out the manual for each command by running man ps , man top , or man htop respectively. The manual includes a comprehensive reference you can check if you need any more help at any point.

Thanks for reading – cheers! 💙

Источник

Оцените статью
Adblock
detector