Pid текущего процесса linux

How to Find the Process ID of a Program and Kill it in Linux

This tutorial teaches you to kill a process in Linux using both its process id and GUI method. This is particularly helpful in killing unresponsive programs.

You can easily stop a program in Linux terminal by pressing the Ctrl+C keys. But you often need to ‘kill’ an unresponsive program. In Windows, you have the task manager for this situation. In Linux, you can kill a process using the command line or GUI task managers. Using the command line is easier. All you have to do is:

  • Finding the PID and killing a running process in the command line
  • Using the top command to find and kill a process
  • Using task managers in Linux desktop to terminate a running process

Let’s start with the command line first.

Method 1: Terminate a process using the kill command

To kill a process, you must know its process ID (PID). The following section tells you how to find the process ID of a program.

Step 1: Find the PID of a process

If you know the name of the process, you can use the command pidof in this fashion:

You can take the help of the tab completion to find the program’s name. The good thing about this command is that it will give the PIDs of all the processes initiated by the program. Here’s an example:

[email protected]:~$ pidof firefox 8980 8871 8821 7228 3796 3742 3741 3590 3381 3355 3085

Finding process ID of a program

If the pidof command doesn’t result in anything, it could mean either there is no process running of that program or the program name you used is incorrect.

You can try the ps command if unaware of the exact program name. This ps command is used for seeing the running processes on the system. You can use the grep command with the program name (or whatever you remember about it).

ps aux | grep -i “name of your desired program” 

The ps aux command returns all the running processes on the system. And the grep afterward shows the line which matches the program name. The output of the command will be like this:

Читайте также:  Простые графические редакторы linux

Find the PID of a process in Linux with ps command

As shown in the picture above, you can get the process ID of the program/process in the second column. Just ignore the line with “–color =auto”.

Step 2: Kill the process using the PID

Once you have the PID of the desired application, use the following command to kill the process immediately:

Here’s an example where I terminate a running instance of the Nautilus file manager. As you can see, Nautilus was no longer running after it was killed. The grep —color=auto -i nautilus is just the grep command running for nautilus search.

Killing process in Linux command line

You can also use the kill command without option -9. Then it requests the process to terminate. With -9 option, it force kills the process immediately. Read more on sigterm and sigkill.

If you have more than one process id, you can kill them together by providing all the PIDs.

sudo kill -9 process_id_1 process_id_2 process_id_3

You can also combine the kill command and the pidof command to kill all the processes of a program.

sudo kill -9 `pidof programe_name`

Of course, you have to replace the program_name with the name of the program you want to kill.

Knowing the program’s name, you can use the magnificent killall command and kill all processes in one single command killall program_name

Method 2: Kill a process using the top command

The top command is one of the popular commands, which is pre-installed on almost all Linux distributions. It is a powerful task management tool. To use it to kill a process, first open the top by entering:

This will open Top and list all the running processes:

top command

Inside the top command, press Shift+L. this will open a “Locate string” prompt, where we can search for the process by name. Once you have located the process that needs to be terminated, press the k key on the keyboard.

Now enter the process ID of the program.

Locate the process and kill using to command

This way, you can terminate any process using the top command. You can also use other system monitoring commands like htop for finding and terminating processes.

Читайте также:  Give all permission to user in linux

Method 3: Killing a process in Linux via GUI

If you are using a Linux desktop, you don’t necessarily have to use the terminal.

There is a task manager in every Linux distribution. It’s usually called a system monitor.

This system monitor is part of the desktop environment. GNOME, KDE, and Cinnamon, all of them have a system monitor. Just look for them in the system menu.

I’ll be demonstrating the GNOME system monitor here.

The default page lists all the running processes. You can kill a process by clicking on it and pressing the End Process button. Or you can right-click on the process and select Kill/End from the context menu.

Search and kill a process using GNOME system monitor

Also, you can note that the process tab lists the process ID of the respective program.

You may also use various third-party tools like Stacer.

What next?

If you are interested in learning more about this topic, I suggest getting familiar with various termination signals.

The ps command is also quite versatile. Learning its usage will be helpful as well.

So, you learned the command line and GUI methods of terminating a running process in Linux.

The command line method is evergreen and you can use it on any Linux distribution, desktop, or server.

Now it’s your turn. Do you prefer the command line method or the GUI tools?

Источник

Работа с процессами в 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 — команда, запустившая процесс.
Читайте также:  Ip адрес интерфейса линукс

Ключи

Ключ Описание
-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 — команда, которая запустила процесс.

Источник

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