Как посмотреть запущенные процессы в linux
Перейти к содержимому

Как посмотреть запущенные процессы в linux

  • автор:

Linux List Processes – How to Check Running Processes

Bolaji Ayodeji

Bolaji Ayodeji

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.

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

The ps command manual page.

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:

  • 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.

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.

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.

Список процессов Linux

На сайте уже есть несколько статей про процессы Linux, в которых подробно описано как ими управлять или как завершить один или группу процессов, но это еще не все. Чтобы правильно управлять процессами и ориентироваться в них вам нужно научиться анализировать список процессов Linux, понимать что значит каждый пункт и зачем он нужен.

В этой статье мы подробно рассмотрим как посмотреть список процессов различными способами, разберем какими бывают процессы, почему так происходит и что с этим делать.

Список процессов в Linux

Я не буду подробно рассказывать про каждую команду, которую можно применять для просмотра списка запущенных процессов, вместо этого мы пройдёмся по основным утилитам для решения этой задачи, рассмотрим как посмотреть список потоков процесса, вывести процессы, которые выполняются на определённом ядре, а также как найти скрытые процессы. Но сначала надо разобраться с терминами.

  • Процесс — если говорить простыми словами, это программа и её данные, загруженные в память компьютера;
  • Дочерний процесс — процессы могут запускать другие процессы для выполнения параллельных задач или других целей такие процессы называются дочерними. Для них выделяется отдельная область в памяти;
  • Поток — поток отличается от процесса тем, что использует ту же память, данные и дескрипторы файлов, что и процесс, в котором он был создан.

1. Утилита ps

Самый простой способ посмотреть список процессов, запущенных в текущей командой оболочке, использовать команду ps без параметров:

Но вряд-ли вас интересует именно это. Чтобы посмотреть все процессы, добавьте опцию -e, а для максимально подробной информации — опцию -F:

Вот значение основных колонок в выводе утилиты:

  • UID — имя пользователя, от имени которого работает процесс;
  • PID — идентификатор пользователя;
  • PPID — идентификатор родительского процесса пользователя;
  • C — расходование ресурсов процессора, в процентах;
  • SZ — размер процесса;
  • RSS — реальный размер процесса в памяти;
  • PSR — ядро процессора, на котором выполняется процесс;
  • STIME — время, когда процесс был запущен;
  • TTY — если процесс привязан к терминалу, то здесь будет выведен его номер;
  • TIME — общее время выполнения процесса (user + system);
  • CMD — команда, которой был запущен процесс, если программа не может прочитать аргументы процесса, он будет выведен в квадратных скобках;

Чтобы посмотреть список процессов в виде дерева, и понимать какой процесс имеет какие дочерние процессы, выполните команду:

Для просмотра списка процессов с потоками используйте опцию -L:

Здесь появятся ещё две дополнительных колонки:

  • LWP — Это сокращение от LightWeight Proccess. Идентификатор потока;
  • NLWP — количество потоков у этого процесса.

Чтобы посмотреть список процессов определенного пользователя, например, sergiy используйте опцию -u:

Теперь давайте перейдём к другим, более интересным, интерактивным утилитам.

2. Утилита top

Утилита top не поставляется вместе с системой, поэтому вам придется её установить. Для этого в Ubuntu выполните:

sudo apt install top

Программа позволяет интерактивно просматривать список запущенных процессов Linux. Чтобы вывести список процессов Linux выполните команду:

Колонки, которые выводит программа очень похожи на ps:

  • PID — идентификатор процесса;
  • USER — имя пользователя, от имени которого выполняется процесс;
  • PR — приоритет планировщика, установленный для процесса;
  • NI — рекомендуемый приоритет процесса. Это значение можно менять, может не совпадать с реальным приоритетом планировщика;
  • VIRT — всё, что находится в памяти, используется или зарезервировано для использования;
  • RES — всё, что находится в оперативной памяти и относится к процессу. Расшифровывается как Resident Memory Size, указывается в килобайтах;
  • SHR — часть памяти из RES, которую занимают ресурсы, доступные для использования другим процессам. Расшифровывается — Shared Memory Size.
  • S — состояние процесса: D — ожидает завершения операции, R — запущен, S — спит, T — остановлен, t — остановлен отладчиком, Z — зомби;
  • %CPU — процент использования ресурсов процессора;
  • %MEM — процент использования ресурсов оперативной памяти на основе колонки RES;
  • TIME — обще процессорное время, которое процесс использовал с момента запуска;
  • COMAND — команда, с помощью которой был запущен процесс.

Для того чтобы сделать вывод программы цветным, нажмите Z:

Чтобы вывести дерево процессов Linux нажмите сочетание клавиш Shift+V:

Для отображения потоков нажмите Shift + H:

Если вам недостаточно стандартных полей с информацией о процессах, вы можете нажать Shift + F и выбрать дополнительные поля, которые надо отображать. Для выбора или удаления поля используйте пробел:

3. Утилита htop

Это ещё более мощная утилита для просмотра запущенных процессов в Linux. Пользоваться ею намного удобнее. Здесь поддерживаются не только горячие клавиши, но и управление мышью. А ещё она выводит всё в цвете, поэтому смотреть на данные намного приятнее. Для установки программы выполните:

sudo apt install htop

Для того чтобы запустить выполните в терминале:

Колонки, которые вы увидите в выводе программы, аналогичны тем, что доступны в top, поэтому я не буду рассматривать их здесь отдельно. Для настройки выводимых данных нажмите кнопку F2, затем перейдите в раздел Display Options:

Здесь надо отметить Tree view для вывода списка процессов в виде дерева, а также снять отметки с пунктов Hide threads. для отображения потоков. Здесь есть как потоки пространства пользователя userland process threads, так и потоки пространства ядра — kernel threads. Теперь всё это будет отображаться:

Для того чтобы настроить какие колонки будут отображаться используйте пункт меню Columns:

Тут вы можете выбрать какие колонки отображать, а какие нет, а также можете настроить их порядок.

4. Программа Gnome Monitor

Вы можете смотреть запущенные процессы не только в терминале, но и в графическом интерфейсе. Для этого можно использовать утилиту Gnome Monitor. У неё намного меньше возможностей, по сравнению даже с ps, но зато у неё есть графический интерфейс. Вы можете запустить программу из главного меню системы:

По умолчанию утилита отображает только процессы текущего пользователя. Если вы хотите получить все процессы кликните по иконке бутерброда и выберите Все процессы:

Теперь программа отображает все запущенные процессы Linux в системе. Здесь вы можете выполнять поиск по процессам, завершать их и многое другое. Но потоков и дерева процессов программа не показывает.

5. Утилита atop

Эта программа тоже позволяет посмотреть процессы в Linux , но немного в другом ключе. Утилиту больше интересует сколько тот или иной процесс потребляет ресурсов системы. Утилита даже может показывать потребление процессами пропускной способности диска и сети, но для этого ей необходим специальный патч ядра. Для установки программы в Ubuntu выполните:

sudo apt install atop

Затем запустите её:

Вот основные колонки, которые выводит утилита и их значения:

  • PID — идентификатор процесса;
  • CID — идентификатор контейнера, используется для контейнеров Docker;
  • SYSCPU — время, потраченное процессом на выполнение в пространстве ядра;
  • USRCPU — время, потраченное процессом на выполнение в пространстве пользователя;
  • VGROW — увеличение использования памяти колонки VIRT за последний период;
  • RGROW — увеличение использования памяти колонки RSS за последний период;
  • ST — статус процесса, N — новый, E — завершенный, S и С — процесс завершен принудительно с помощью сигнала;
  • EXC — код выхода или код сигнала, которым был завершен процесс;
  • THR — общее количество потоков в этом процессе;
  • S — состояние процесса, аналогично описанному для top;
  • CPUNR — номер ядра процессора, на котором запущен основной поток процесса;
  • CPU — процент использования ресурсов процессора;
  • CMD — команда, которой была запущена программа;
  • MEM — процент использования памяти;

Для того чтобы включить отображение потоков процесса нажмите y:

Для просмотра информации о памяти нажмите m, если хотите вернутся обратно, нажмите g:

Выводы

В этой статье мы разобрали самые основные способы посмотреть список процессов в Linux, как видите есть простые способы, но есть и более сложные и информативные. Какими способами вы пользуетесь чаще всего? Напишите в комментариях!

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

How to List Running Processes in Linux: A Beginner’s Guide

Need to view all running processes on your Linux server and discover which consumes your resources the most? Look no further, because, in this article, we’ll explain how to list processes by using several common Linux commands.

Introduction to Linux Processes

A process is the execution of a program. They can be launched when opening an application or when issuing a command through the command-line terminal. However, an application can run multiple processes for different tasks. For instance, Google Chrome will start a different process each time a new tab is opened.

A process can be initiated as a foreground or background process. Each Linux process is assigned a unique PID (process identification number).

Occasionally, processes may consume a lot of resources and need to be killed. Alternatively, times when you may want to change the priority level of a process, so the system will allocate more resources to it. Regardless of the case, all these tasks require you to do the same thing: listing the running processes on Linux.

How to List Running Processes in Linux?

To list processes in Linux, use one of the three commands: ps, top or htop. Ps command provides static snapshot of all processes, while top and htop sorts by CPU usage.

Let’s dive further into each of them.

Utilizing the “ps” Command

The ps (process statuses) command produces a snapshot of all running processes. Therefore, unlike the Windows task manager, the results are static.

Listing Linux running processes with ps command

When this command is used without any additional argument or option, it will return a list of running processes along with four crucial columns: the PID, terminal name (TTY), running time (TIME), and the name of the command that launches the process (CMD). You can use ps aux to get more in-depth information about your running processes. Here’s a breakdown of each argument:

  • a option outputs all running processes of all users in the system.
  • u option provides additional information like memory and CPU usage percentage, the process state code, and the owner of the processes.
  • x option lists all processes not executed from the terminal. A perfect example of this are daemons, which are system-related processes that run in the background when the system is booted up.

Listing running processes using ps aux command

Using the ps -axjf command

If you want to list Linux processes in a hierarchical view, use the ps -axjf command. In this format, the shell will put child processes under their parent processes. Aside from those two options, here are some other common examples of the ps command that list running processes in Linux:

  • ps -u [username] lists all running processes of a certain user.
  • ps -e or ps -A displays active Linux processes in the generic UNIX format.
  • ps -T prints active processes that are executed from the terminal.
  • Ps -C process_name will filter the list by the process name. In addition, this command also shows all child processes of the specified process.

Using the “top” Command

The top command is used to discover resource-hungry processes. This Linux command will sort the list by CPU usage, so the process which consumes the most resources will be placed at the top. It’s also useful to check if a specific process is running.

Using the top command

Unlike the ps command, the output of the top command is updated periodically. That means you’ll see real-time updates for CPU usage and running time. Once the shell returns the list, you can press the following keys to interact with it:

Listing running processes using htop command

Once installed, type htop, and you’ll get a list of all your Linux processes. Just like the previous command, htop also has several keyboard shortcuts:

Listing running processes using atop command

Here is the list of available arguments and their descriptions:

Command Description
man atop Displays the atop command manual page.
atop -l Displays the average-per-second total values.
atop -a Displays the active processes during the last intervals.
atop -c Displays the command line per process.
atop -m Displays the memory-related information.
atop -d Displays the disk-related information.
atop -n Displays the network information.
atop -s Displays the scheduling details.
atop -v Displays the various info (for example PPID, user, or time).
atop -y Displays the individual threads.

Once atop is running, press the shortcut keys listed below to sort processes:

Keys Functions
a Sorts in order of the most active resources.
c Reverts to sorting by the CPU consumption (default).
d Sorts in order of disk activity.
m Sorts in order of memory usage.
n Sorts in order of network activity.

Conclusion

It is important to know how to list all running processes in your Linux operating system. The knowledge will be useful when you need to manage processes.

Which of the three commands do you prefer? Share your thoughts in the comment section below!

Sorry, you have been blocked

This website is using a security service to protect itself from online attacks. The action you just performed triggered the security solution. There are several actions that could trigger this block including submitting a certain word or phrase, a SQL command or malformed data.

What can I do to resolve this?

You can email the site owner to let them know you were blocked. Please include what you were doing when this page came up and the Cloudflare Ray ID found at the bottom of this page.

Cloudflare Ray ID: 7e4b46039dc677b0 • Your IP: Click to reveal 88.135.219.175 • Performance & security by Cloudflare

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *