- Как убить процесс Linux
- Как происходит завершение процесса?
- Как убить процесс Linux?
- Как завершить процесс с помощью pkill
- Как остановить процесс с помощью killall
- Выводы
- How to Kill a Process in Linux Command Line
- Termination signals in Linux
- Getting the PID of a process
- Terminating a process in the Linux command line
- Using kill command
- Using killall command
- Using pkill command
- 10+ examples for killing a process in Linux
- List running processes
- Kill a process by PID
- Default signal sent by the kill command
- Force killing
- How to kill all processes by name?
- How to kill all processes by a user?
- How to kill a nohup process?
- How to run a process in the background?
- Using screen command
- How to kill a background process?
- How to kill stopped processes?
- Kill operation not permitted
Как убить процесс Linux
Несмотря на то что Linux стабильнее чем Windows, в плане работы программ и различных сервисов, случается всякое и иногда возникает необходимость завершить процесс Linux. Это может понадобиться, если программа завила, когда вы запустили системный сервис в фоне через терминал, а не систему инициализации, а также во многих других случаях, когда убить процесс Linux проще, чем перезагружать всю систему.
В этой статье мы рассмотрим несколько самых распространенных способов завершить процесс Linux. Опишем подробно как происходит остановка процесса и как все сделать правильно.
Как происходит завершение процесса?
Управление процессами в операционной системе Linux осуществляется с помощью сигналов. В том числе и завершение любого процесса. Сигналы передает система, но также их может передавать пользователь с помощью специальных команд или даже сочетаний клавиш в терминале. Когда процессу приходит сигнал о необходимости завершиться, он должен выполнить некоторые подготовительные действия.
Необходимо завершить дочерние процессы, удалить временные файлы, сокеты и так далее. Но в зависимости от сложности ситуации процесс может реагировать не на все сигналы. Рассмотрим основные сигналы, которые используются для завершения процесса:
- SIGINT — самый безобидный сигнал завершения, означает Interrupt. Он отправляется процессу, запущенному из терминала с помощью сочетания клавиш Ctrl+C. Процесс правильно завершает все свои действия и возвращает управление;
- SIGQUIT — это еще один сигнал, который отправляется с помощью сочетания клавиш, программе, запущенной в терминале. Он сообщает ей что нужно завершиться и программа может выполнить корректное завершение или проигнорировать сигнал. В отличие от предыдущего, она генерирует дамп памяти. Сочетание клавиш Ctrl+/;
- SIGHUP — сообщает процессу, что соединение с управляющим терминалом разорвано, отправляется, в основном, системой при разрыве соединения с интернетом;
- SIGTERM — немедленно завершает процесс, но обрабатывается программой, поэтому позволяет ей завершить дочерние процессы и освободить все ресурсы;
- SIGKILL — тоже немедленно завершает процесс, но, в отличие от предыдущего варианта, он не передается самому процессу, а обрабатывается ядром. Поэтому ресурсы и дочерние процессы остаются запущенными.
Важно понимать, что нужно дать процессу возможность завершиться корректно. Желательно, чтобы порты и сокеты были освобождены, закрыты и удаленны временные файлы. Поэтому никогда не передавайте сразу SIGKILL. Передавайте сигналы завершения в последовательности, как они перечислены выше.
Сначала Ctrl+C, если это возможно, затем SIGTERM — он хоть и завершает процесс, но делает эту культурно, и только в крайнем случае SIGKILL. А теперь рассмотрим как убить процесс по pid Linux на практике. Если вы всегда используете SIGKILL, тогда на ум приходит такая картинка:
Как убить процесс Linux?
Для передачи сигналов процессам в Linux используется утилита kill. Ее синтаксис очень прост:
$ kill -сигнал pid_процесса
Сигнал представляет собой один из выше перечисленных сигналов для завершения процесса. По умолчанию, если этот параметр не указан, используется сигнал SIGTERM, что является очень правильно. Также нам нужно указать какой процесс нужно завершить. Для этого используется уникальный идентификатор процесса — PID.
Допустим, у нас выполняется утилита ping. Мы хотим ее завершить с помощью kill. Тогда, сначала мы узнаем ее идентификатор с помощью команды ps:
ps aux | grep ping
В первой строчке отобразится сама утилита ping, а во второй сама программа ps. Берем нужный PID и завершаем процесс с помощью SIGTERM:
kill -TERM 20446
И только если после этой команды процесс продолжил висеть, а это вы можете проверить, выполнив ps. Только теперь можно выполнить SIGKILL:
kill -KILL 20446
Теперь снова проверяем:
Если процесс запущен от суперпользователя, то, естественно, вам нужно использовать sudo. Не всегда удобно уничтожать процесс по его PID, как минимум, потому, что вам этот PID нужно еще узнать. Мы могли бы нагородить сложных конструкций с использованием xargs, чтобы вычислять автоматически pid по имени процесса и сразу же его завершать, но в этом нет необходимости. Уже существуют специальные утилиты.
Как завершить процесс с помощью pkill
Утилита pkill — это оболочка для kill, она ведет себя точно так же, и имеет тот же синтаксис, только в качестве идентификатора процесса ей нужно передать его имя. Утилита сканирует директорию proc и находит PID первого процесса с таким именем, затем отправляет ему SIGTERM. Таким образом, вы можете убить процесс по имени Linux. Например, если мы хотим завершить тот же ping:
Также можно вручную задать тип сигнала:
pkill -TERM ping
Вместо ps, вы можете использовать утилиту pgrep для поиска pid процесса, убедимся что наша программа завершена:
Но если вам программа создала несколько процессов, например, браузер chromium или firefox создают отдельный процесс для каждой из вкладок, то эта утилита мало чем поможет. Тут нужен следующий вариант.
Как остановить процесс с помощью killall
killall работает аналогично двум предыдущим утилитам. Она тоже приминает имя процесса в качестве параметра и ищет его PID в директории /proc. Но эта утилита обнаружит все процессы, с таким именем и завершит их. Например:
Как видите, запущено несколько процессов, осталось остановить процесс Linux с помощью killall:
Команда завершит все запущенные утилиты ping, вы можете убедиться в этом еще раз выполнив pgrep:
Выводы
В этой статье мы рассмотрели как убить процесс Linux. Иногда эта задача может быть очень полезной, но важно понимать, что ее нужно выполнять правильно. Нельзя сказать, что передача SIGKILL вместо SIGTERM очень опасна, но так делать не стоит. Надеюсь, эта информация была полезна для вас.
How to Kill a Process in Linux Command Line
It has been an awesome day on your Linux system, and suddenly a process starts to slow down the whole computer. It is not that important, and you want to stop its execution.
If the command/process is running in the foreground, you can use the Ctrl+C terminal shortcut. However, if the process is not visible (running in the background), you can use dedicated commands to ‘kill it’.
The term «killing a process» refers to stopping a process mid execution. If you know the process ID (PID), you can use the kill command like this:
In the above syntax, signal refers to the kill signal you want to send for termination and PID refers to the ID of the process.
There is also a killall command and I’ll discuss both kill and killall commands in this article.
Before you start killing processes, you should know a few things. Such as what termination signals are available, how to find PID etc.
Let’s start with the signals first.
Termination signals in Linux
When a process is terminated by the OS or by the user i.e. the process did not finish on its own, it is sent a terminal signal.
Below are the available termination signals:
Signal | Numerical Value | Description |
---|---|---|
SIGHUP | 1 | Signal Hangup: Sent to a process when the terminal controlling it is closed. |
SIGINT | 2 | Signal Interrupt: The signal sent to a process when a user terminates a process. (eg Ctrl + X) |
SIGKILL | 9 | Signal Kill: The signal that immediately quits a process, without allowing it to save its current state. |
SIGTERM | 15 | Signal Terminate: Sent to the signal to request termination of process. This signal can be ignored by a process. But this is the preferred way of terminating a process as it can release the resources when the process receives SIGTERM. |
SIGSTOP | 19 (for x86, ARM and most others) 17 (for Alpha) 23 (for MIPS) 24 (for PARISC) | Signal Stop: Signal for stopping a process, but to be resumed at a later time. |
It is most likely that you’ll be using signals 9 and 15. Read more about the difference between SIGKILL and SIGTERM.
Getting the PID of a process
You also need to know the details of the process you want to terminate. With kill command, you must provide the id of a process (PID). You can get the PID from the process name:
Terminating a process in the Linux command line
Let’s see the kill command first as you’ll be using it more than killall.
Using kill command
The kill command requires that you know the ID of a process that you want to kill and, optionally, the termination signal.
To simply kill a command, use the following syntax:
Sending a termination signal to a PID is optional, and if no signal is provided, kill defaults to sending SIGTERM ( 15 ), ending in a graceful termination of said process.
I started a background process of sleep command (and it gave me a PID). Let’s try killing it using the kill command.
Killing this particular instance of sleep would look like the following:
If I wanted to use a termination signal, I could either use the numerical value or the signal itself:
Using killall command
If you do not know what the PID of a process is, or if the said process has multiple child processes, and you want to kill the child processes and the parent process at once, you can use killall command.
Similar to kill command, specifying a termination signal is optional. When no termination signal is specified, killall will send SIGTERM ( 15 ) to gracefully shut down said process.
To demonstrate the use of killall , I want to kill two running sleep commands.
Additionally, you can use the -e flag to find an exact match of the process name.
Using pkill command
An alternative command to kill is the pkill command. It is a «combination» of pgrep and kill command.
The killall kills all the processes that have a matching name. On the other hand, pkill uses pattern matching to match processes and kills them.
Below is the syntax:
A few useful options available in pkill command as following:
- -u : Processes owned by a particular owner
- -x : Processes that match pattern exactly
- -signal : Specify a termination signal (default is SIGTERM)
Assuming I have a user guest on my computer who should not have any processes running currently, and if there are, I want to terminate them. How can I do that?
Note that I used sudo because I was dealing with processes that did not belong to my user.
With this article, you learned 3 different commands for killing a process in Linux. I feel it will be the kill command that you more than the others. Am I right?
10+ examples for killing a process in Linux
In this tutorial, we will talk about killing a process in Linux with multiple examples. In most cases, its as simple as typing kill command followed by the process ID (commonly abbreviated as PID).
As you can see, weve killed a process with the ID of 1813.
If you are a Windows user, it may help to think of the kill command as Linuxs equivalent of the End task button inside of the Windows task manager.
Table of Contents
List running processes
The ps -e command will list everything running on your system. Even with a minimal installation, the command will probably output more than 80 results, so its much easier to pipe the command to grep or more.
In the screenshot below, we check to see if SSH is running on the system.
This also gives us the PID of the SSH daemon, which is 1963.
Pipe to more if you want to look through your systems running processes one-by-one.
You can also make use of the top command in order to see a list of running processes. This is useful because it will show you how many system resources that each process is using.
The PID, User, and name of the resource are all identified here, which is useful if you decide to kill any of these services later.
Pay attention to the %CPU and %MEM columns, because if you notice an unimportant process chewing up valuable system resources, its probably beneficial to kill it!
Another very efficient away of obtaining the corresponding process ID is to use the pgrep command. The only argument you need to supply is the name (or part of the name) of the running process.
Heres what it looks like when we search for SSH. As you can see, it returns a process ID of 2506.
Kill a process by PID
Now that we know the PID of the SSH daemon, we can kill the process with the kill command.
You can issue a final ps command, just to ensure that the process was indeed killed.
The results come up empty, meaning that the process was shut down successfully. If you notice that the process is continuing to run — which should not normally happen — you can try sending a different kill signal to the process, as covered in the next session.
Note: Its not always necessary to use sudo or the root user account to end a process. In the former example, we were terminating the SSH daemon, which is run under the root user. Therefore, we must have the appropriate permissions to end the process.
Default signal sent by the kill command
By default, the kill command will send a SIGTERM signal to the process you specify.
This should allow the process to terminate gracefully, as SIGTERM will tell the process to perform its normal shutdown procedures — in other words, it doesnt force the process to end abruptly.
This is a good thing because we want our processes to shut down the way they are intended.
Sometimes, though, the SIGTERM signal isnt enough to kill a process. If you run the kill command and notice that the process is still running, the process may still be going through its shutdown process, or it may have become hung up entirely.
Force killing
To force the process to close and forego its normal shutdown, you can send a SIGKILL signal with the -9 switch, as shown here:
It can be tempting to always append the -9 switch on your kill commands since it always works. However, this isnt the recommended best practice. You should only use it on processes that are hung up and refusing to shut down properly.
When possible, use the default SIGTERM signal. This will prevent errors in the long run, since it gives the process a chance to close its log files, terminate any lingering connections, etc.
Apart from the SIGTERM and SIGKILL signals, there is a slew of other signals that kill can send to processes, all of which can be seen with the -l switch.
The numbers next to the names are what you would specify in your kill command. For example, kill -9 is SIGKILL, just like you see in the screenshot above.
For everyday operations, SIGTERM and SIGKILL are probably the only signals you will never need to use. Just keep the others in mind in case you have a weird circumstance where a process recommends terminating it with a different signal.
How to kill all processes by name?
You can also use the name of a running process, rather than the PID, with the pkill command. But beware, this will terminate all the processes running the under the specified name, since kill wont know which specific process you are trying to terminate.
Check out the example below, where we terminate five processes with a single pkill command.
In this example, we had wanted to only terminate one of those screen sessions; it wouldve been necessary to specify the PID and use the normal kill command. Otherwise, there is no way to uniquely specify the process that we wish to end.
How to kill all processes by a user?
You can also use the pkill command to terminate all processes that are running by a Linux user. First, to see what processes are running under a specific user, use the ps command with a -u switch.
That screenshot shows us that there are currently five services running under the user geek. If you need to terminate all of them quickly, you can do so with pkill.
How to kill a nohup process?
You can kill the nohup process the same way as any other running process. Note that you cant grep for nohup in the ps command, so youll need to search for the running process using the same methods as shown above.
In this example, we find a script titled test.sh which has been executed with the nohup command. As youll see, finding and ending it is much the same as the examples above.
The only difference with the output is that the shell notifies us that the process was terminated. Thats not part of kill, but rather a result from running the script in the background (the ampersand in this example) and being connected to the same tty from which the script was initiated.
How to run a process in the background?
The kill command is an efficient way to terminate processes you have running in the background. Youve already learned how to kill processes in this tutorial, but knowing how to run a process in the background is an effective combination for use with the kill command.
You can append an ampersand (&) to your command in order to have it executed in the background. This is useful for commands or scripts that will take a while to execute, and you wish to do other tasks in the meantime.
Here we have put a simple ls command into the background. Since its the type of command which takes very little time to execute, were given more output about it finishing its job directly after.
The output in our screenshot says Done, meaning that the job in the background has completed successfully. If you were to kill the job instead, it would show terminated in the output.
You can also move a job to the background by pressing Ctrl+Z on your keyboard. The ^Z in this screenshot indicates that we pressed Ctrl+Z and the test.sh script moved into the background.
You can see test.sh continuing to run in the background by issuing a ps command.
Using screen command
Another way to run a process in the background is to use the screen command. This works by creating what basically amounts to a separate terminal window (or screen and hence the name).
Each screen that you create has its process ID, which means that its an efficient way of creating background processes that can be later terminate using the kill command.
Screen command doesnt come with all Linux installs by default, so you may have to install it.
On Ubuntu and Debian-based distributions, you can install it with the following command:
Once you installed the screen command, you can create a new session by just typing screen.:
But, before you do that, its good to get in the habit of specifying names for your screens. That way, they are easy to look up and identify later. All you need in order to specify a name is the -S switch.
Lets make a screen called testing and then try to terminate it with the kill command. We start like this:
After typing this command and pressing enter, were instantly taken to our newly created screen. This is where you could start the process that you wish to have running in the background.
This is especially handy if you are SSHd into a server and need a process to continue running even after you disconnect.
With your command/script running, you can disconnect from the screen by pressing Ctrl+A, followed by D (release the Ctrl and A key before pressing the D key).
As you can see, the screen command has listed the process ID as soon as we detached the screen. Of course, we can terminate this screen (and the command/script running inside of it), by using the kill command.
You can easily look up the process ID of your screen sessions by using this command:
If we hadnt named our screen session by using the -S switch, only the process ID itself would be listed. To reattach to the any of the screens listed, you can use the -r switch:
In the screenshot below, we are killing the screen session we created (along with whatever is being run inside of it), and then issuing another screen -ls command in order to verify that the process has indeed ended.
How to kill a background process?
In one of our examples in the previous section, we put our tesh.sh script to run in the background. Most background processes, especially simple commands, will terminate without any hassle.
However, just like any process, one in the background may refuse to shut down easily. Our test.sh script has a PID of 2382, so well issue the following command:
In the screenshot, though, youll notice that the script has ignored our kill command:
As weve learned already, kill -9 is the best way to kill a process that is hung up or refusing to terminate.
How to kill stopped processes?
It can be useful to kill all your stopped background jobs at once if they have accumulated and are no longer useful to you. For the sake of example, were running three instances of our test.sh script in the background and theyve been stopped:
You can see these processes with the ps command:
Or, to just get a list of all the stopped jobs on the system, you can run the jobs command:
The easiest way to kill all the stopped jobs is with the following command:
Or use the -9 switch to make sure the jobs terminate immediately:
The `jobs -ps` command will list all jobs PIDs running in the background, which is why were able to combine its output with the kill command in order to end all the stopped processes.
Kill operation not permitted
If you are getting an operation not permitted error when trying to kill a process, its because you dont have the proper permissions. Either log in to the root account or use sudo (on Debian distributions) before your kill command.
I hope you find the tutorial useful. Keep coming back.