Закрыть по pid linux

Закрыть по pid linux

NAME

kill - send a signal to a process

SYNOPSIS

DESCRIPTION

The default signal for kill is TERM. Use -l or -L to list available signals. Particularly useful signals include HUP, INT, KILL, STOP, CONT, and 0. Alternate signals may be specified in three ways: -9, -SIGKILL or -KILL. Negative PID values may be used to choose whole process groups; see the PGID column in ps command output. A PID of -1 is special; it indicates all processes except the kill process itself and init.

OPTIONS

 [. ] Send signal to every listed. - -s --signal Specify the signal to be sent. The signal can be specified by using name or number. The behavior of signals is explained in signal(7) manual page. -l, --list [signal] List signal names. This option has optional argument, which will convert signal number to signal name, or other way round. -L, --table List signal names in a nice table. NOTES Your shell (command line interpreter) may have a built-in kill command. You may need to run the command described here as /bin/kill to solve the conflict.

EXAMPLES

kill -9 -1 Kill all processes you can kill. kill -l 11 Translate number 11 into a signal name. kill -L List the available signal choices in a nice table. kill 123 543 2341 3453 Send the default signal, SIGTERM, to all those processes.

SEE ALSO

kill(2), killall(1), nice(1), pkill(1), renice(1), signal(7), skill(1)

STANDARDS

This command meets appropriate standards. The -L flag is Linux-specific.

AUTHOR

Albert Cahalan ⟨albert@users.sf.net⟩ wrote kill in 1999 to replace a bsdutils one that was not standards compliant. The util-linux one might also work correctly.

REPORTING BUGS

© 2019 Canonical Ltd. Ubuntu and Canonical are registered trademarks of Canonical Ltd.

Источник

Завершить процесс в Linux – команды ps, kill и killall

Как бы там ни было, но некоторые приложения в Linux иногда зависают. При этом бывают ситуации, когда приложение вообще не отзывается, либо работает так медленно, что корректно завершить его работу не представляется возможным. Чтобы оперативно выйти из получившейся ситуации можно «убить» данный процесс. Для этог используеются команды kill и killall. Сейчас мы разберемся как использоваться эти команды, находить PID процесса и посылать сигнал SIGKILL.

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

Определить PID процесса — команда pidof

PID — уникальный идентификатор процесса в системе Linux. Чтобы корректно выполнить остановку процесса сначала стоит определить его PID. Для этого используются команды ps и grep. В свою очередь команда ps предназначена для вывода списка активных процессов в системе и информации о них. Команда grep запускается одновременно с ps (в канале) и будет выполнять поиск по результатам команды ps. Вывести список всех процессов можно, выполнив в командной строке:

Разумеется, PID можно определить и через top. Но в большинстве случаев количество процессов слишком велико (и динамически меняется в top), поэтому быстро и правильно определить PID не так уж и просто. Как раз для этого используется команда grep. Например, для завершения процесса браузера Google Chrome необходимо выполнить следующую команду:

ps axu | grep chrome

[itechf2@////// ~]$ ps axu | grep chrome
itechf2 20474 2.7 1.5 938416 120136 tty2 Sl+ 11:07 0:00 /opt/google/chrome/chrome

В нашем случае 20474 и есть искомый PID. Более простой способ — использовать команду pidof, при этом необходимо указывать имя процесса. Например:

[itechf2@///// ~]$ pidof chrome
20728 20706 20668 20647 20586 20574 20553 20508 20474

Завершить процесс в Linux — команды kill и killall

Завершить процесс в операционной системе Linux, зная его PID, можно командой kill. Стоит знать и понимать: команда kill предназначена для посылки сигнала процессу. По умолчанию, если мы не указываем какой сигнал посылать, посылается сигнал SIGTERM (от слова termination — завершение). SIGTERM указывает процессу на то, что необходимо завершиться. Каждый сигнал имеет свой номер. SIGTERM имеет номер 15. Список всех сигналов (и их номеров), которые может послать команда kill, можно вывести, выполнив kill -l. Чтобы послать сигнал SIGKILL (он имеет номер 9) процессу 2811, выполните в командой строке:

При этом, сигнал SIGTERM может и не остановить процесс (например, при перехвате или блокировке сигнала), SIGKILL же выполняет уничтожение процесса всегда, так как его нельзя перехватить или проигнорировать.

Команда killall в Linux предназначена для «убийства» всех процессов, имеющих одно и то же имя. Это удобно, так как нам не нужно знать PID процесса. Например, мы хотим закрыть все процессы с именем chrome. Выполните в терминале:

Команда killall, также как и kill, по умолчанию шлет сигнал SIGTERM. Чтобы послать другой сигнал нужно воспользоваться опцией -s. Например:

Занимаюсь IT с 2007 года. Всё началось с увлечения — разгона компьютерного оборудования. Много воды и азота утекло с тех пор. Сейчас уже более 3х лет со своей командой оказываю комплексную поддержку и продвижение бизнеса: SEO, Яндекс.Директ, рассылки и удалённое обслуживание серверов. Буду рад помочь, обращайтесь!

Источник

Linux Kill Process by PID

In Linux (and most modern operating systems), terminating a process forcefully requires sending an appropriate terminal signal. There are multiple ways to send a termination signal to a particular process. If you know the PID (process ID) of the target process, then the kill command can directly send the termination signal to it.

In this guide, we will demonstrate how to kill a Linux process by its PID.

PID in Linux

The term PID is an acronym for “process identification number”. Each process is assigned a unique PID the moment they’re created on the system. The PID number 1 is assigned to systemd (init, for older systems). Essentially, systemd or init is always the first process to start on Linux and is parent to all other processes.

There are a couple of tools we can use to get the PID of a target process. The most popular (and recommended) method of getting the PID is using the ps command. It’s a built-in tool available on all Linux systems. Learn more in-depth about the ps command in Linux.

To print all the running processes with their PID, run the following ps command:

For easier navigation, pipe the output to the less command:

Notice that the PID column lists all processes sorted by PID. It’s the value that we are looking for.

Looking for a particular process with a specific name? Then the grep command is your friend. It can search for a particular pattern in the given file (STDOUT, in this case). For example, the following command will search for any running Firefox process:

If you know the name of the target process, then we can use the pidof command to directly get the PID.

Another interesting command to do the job is pgrep. It directly operates on the list of currently running processes. The pgrep command will take the process name as the parameter and print the PID of any matching entry.

Note the PID of the target process. The next section of this article will showcase terminating the process by its PID.

Killing a Process

Killing a process requires sending a terminal signal to the process. However, there isn’t a single termination signal. There are several of them, each acting slightly differently than the others. So, it’s crucial to understand them first.

Linux Kill Signals

The kill command in Linux is responsible for sending the termination signals. For a detailed explanation, check out this guide on the Linux kill command. In short, you tell the kill command what signal to send to which process (using PID).

To get the complete list of all the termination signals, run the following command:

For the most part, however, we will need only a handful of them. Here are detailed explanations of the most common termination signals you should know about.

  • SIGUP (1) – The controlling terminal is hung up or the controlling process is dead. In such a situation, SIGUP will reload the configuration files and open/close log files.
  • SIGKILL (9) – It’s a direct kill signal to the target process. It should be used as the last resort to terminate a process. If a process is terminated using SIGKILL, then it won’t save data or cleaning upon the termination of the process.
  • SIGTERM (15) – It sends a termination signal to the target process. SIGTERM is the default signal to send. It’s also considered the safest method of terminating a process.

Killing a Process Using Kill

This is the default way of terminating a target process on Linux. The kill command follows the following command structure:

For example, to send SIGTERM to a process, the command would look like this:

Similarly, if you want to send SIGKILL, then use the following command:

Learn more about the Linux kill command with in-depth explanations and examples.

Killing Multiple Processes Using Killall

The killall command acts similar to kill. However, instead of defining a specific PID, it uses the process name and sends the specified termination signal to all processes that match the name.

The command structure of killall looks like this:

For example, the following killall command will send SIGTERM to all the running Firefox processes:

Check out this guide on the Linux killall command for detailed explanations with examples. It’s also recommended to check out the man page of killall:

Killing Multiple Processes Using pkill

Similar to the killall command, pkill can also lookup processes based on the name and send the specified termination signal. The command structure is almost similar as well;

For example, use the following pkill command to terminate the Firefox process with SIGTERM:

As always, check the man page of pkill for in-depth explanations with all the nuances:

Final Thoughts

This guide showcases various ways of killing a process by its PID. It also demonstrates alternative methods using the process name instead of PID. It’s always better to have multiple tools at your disposal. Here, we used ps and pgrep commands to find the PID and kill, pkill, and killall commands for killing processes.

In many situations, you may want to get rid of pesky background processes that are malfunctioning. Learn more about identifying background processes in Linux. Then, following the methods in this guide, you can easily get rid of unwanted ones.
Happy computing!

About the author

Sidratul Muntaha

Student of CSE. I love Linux and playing with tech and gadgets. I use both Ubuntu and Linux Mint.

Источник

Читайте также:  Командная строка linux php
Оцените статью
Adblock
detector