How to Kill a Process in Linux
Tasks in Linux are called processes. Every process has a unique process ID. In this tutorial, we’ll show you how to terminate a process using Linux commands, to improve your VPS management skills.

What Is Kill Command Used For?
Sometimes, you might start a server or an application, forget about it, and need to shut it off. In such scenarios, we can use the kill command.
Below are a few examples where the kill command can be helpful:
- To stop any automated process
- To stop a process that has been started by accident
- To stop a process that consumes a lot of memory
- To force stop any process running in Linux
- To stop a background process
Apart from stopping a process, the kill command can provide several features. Like, send a signal to a process. By default, this is taken as a TERM signal which will terminate the process.
How to Show the Process ID in Linux
Kill commands lets you terminate a process by using a specific process ID, also known as a pid. To show a pid in Linux you can execute the following command:
This will list all the available processes with a pid. If you want to make your list more specific – add a grep command like this:
This will display all java processes running in the output.
How to Show All Kill Command Signals
There are multiple signals available in Linux which can be used to interrupt, terminate, or pause processes. The command can be used as below:
This command will display a manual page entry of the different kill signals with their names and corresponding numbers. While there are multiple signals available, in most cases we would use SIGKILL (9) and SIGTERM (15).
How to Kill a Process in Linux Using the Terminal
Now we’re ready to move on and learn all the different uses of the Kill Command. To follow along, access your virtual private server using SSH.
Using the Kill Command with a PID
To kill a specific process with a PID use the following command:
Here 63772 is the pid for a process we want to terminate. Since no signal is specified this will be SIGTERM signal. Sometimes, this may not work; in that case, you may have to kill a process forcefully.
In such cases, you can use the command format as shown below:
Below is a sample command to forcefully kill the process:
Similarly, to kill using the shorter option you can use:
Replace 63772 with the relevant pid for the process to be terminated.
How to Kill Multiple Processes in Linux
With the same command, you can kill multiple processes. The syntax for this command would be:
Here’s an example showing how it would look in the real world:
How to Kill a Process in Linux Using the Pkill Command
Pkill is a flavor of the kill command where you can specify the process name or a pattern to find a process:
The above command will kill the chrome browser. You can also specify a partial name match in the command line such as:
However, this command carries a risk of sometimes killing the wrong process, especially when there are multiple processes with the same name.
You can check the list by using the complete process name:
The above command can be used when you know the complete name of the process.
You can check for matching processes by using a partial name:
This command will list the process with the corresponding process ID.
How to Kill a Process in Linux Using the Killall Command
The basic difference between killall and kill is that killall can terminate the process by name while the kill command uses the pid.
An example of such command is:
This is similar to pkill. However, killall does an exact name match, while pkill can do a pattern match. This is one of the reasons, killall is safer compared to pkill.
One more difference is the root package to which these commands belong. In Linux, killall belongs to the psmisc package. On the other hand, commands such as ps, top, kill, pkill belong to procps package.
Another difference is that killall can be customized to terminate processes based on timestamps. In case you want to kill a process that has been running for less than 40 minutes, then you can use:
You can similarly use the below options together with the killall command:
- s – seconds
- m – minutes
- h – hours
- d – days
- w -weeks
- M – months
- y – years
Conclusion
This covers the most important and useful kill commands. To further learn about this essential utility you can refer to the Linux manual. Good luck with your project, see you in the next tutorial!
How to Kill a Process in Linux? Commands to Terminate
If a Linux process becomes unresponsive or is consuming too many resources, you may need to kill it.
Most processes have their own methods of shutting down. Unfortunately, processes can malfunction and not allow themselves to be shut down. If a running background process is unresponsive, it becomes necessary to use a command to kill it.
Here’s a complete guide on how to kill a Linux process using the command line.

What Processes Can You Kill in Linux?
Before killing or terminating a process, you need to consider permissions.
A root user can kill all processes. You can either add sudo before a command to run it as root, or obtain a root shell with su . Then execute the command.
Killing a process sends a termination message to the given process. There are multiple types of termination messages including:
- SIGKILL – SIGKILL is the ultimate way of killing a process. It will always kill a process and will kill the process abruptly, generating a fatal error. SIGKILL should always work. If it does not work, the operating system has failed.
- SIGTERM – SIGTERM attempts to kill a process, but unlike SIGKILL it may be blocked or otherwise handled. It can be considered a gentler way of attempting to terminate a process.
For most purposes, SIGKILL will be the fastest and most effective method to terminate the process.
Step 1: View Running Linux Processes
The top command is the easiest way to get a complete overview of the processes currently being run.
To view a list of all currently running processes, use the command:
The top command will reveal process IDs and users, in addition to the amount of memory and CPU power each process is using.

To kill processes directly from the top interface, press k and enter the process ID.
To exit the top interface, press q.
Step 2: Locate the Process to Kill
Before you can kill a process, you need to find it. There are multiple ways you can search for a process in Linux. Processes can either be located by a process name (or a partial process name) or a process ID (also known as a “pid”).
Locate a Process with ps Command
The ps command displays similar information to top , though it will not be in the form of an interface. Instead, the ps command provides a complete listing of running processes, formatted based on the tags you add.
The most common options to add to this is “-aux”:
- -a . View processes of all users rather than just the current user.
- -u . Provide detailed information about each of the processes
- -x . Include processes that are controlled not by users but by daemons.
For example, the command ps -aux will return a detailed process list of all processes.

Finding the PID with pgrep or pidof
The Linux command pgrep is a more complex way of finding a process. This command will return processes based on specific selection criteria, which is known as the pattern. The pattern is a regular expression, such as a* , where * would be a wildcard.
Here are the options that can be used with this command:
- -l . List both the process names and the PIDs.
- -n . Return the process that is newest.
- -o . Return the process that is oldest.
- -u . Only find processes that belong to a specific user.
- -x . Only find processes that exactly match the given pattern.
The command pgrep -u root displays all processes owned by root. The command pgrep -u root 'a*' returns processes owned by root that start with the letter “a”.
The pidof command is used to find the ID of a process, provided that you know the name of the process.
A few options can be included, such as:
- -c . Only return PIDs within a single root directory.
- -o . Omit certain PIDs (include the processes to omit after the flag).
- -s . Only return a single PID.
- -x . Also returns PIDs of shells that are running scripts.
Step 3: Use Kill Command Options to Terminate a Process
There are a few different methods of killing a process in Linux, depending on whether you know the name of the process running, the pid of the process, or just how long the process has been running.
killall Command
The killall command is used to kill processes by name. By default, it will send a SIGTERM signal. The killall command can kill multiple processes with a single command.
Several options can be used with the killall command:
- -e . Find an exact match for the process name.
- -I . Ignore case when trying to find the process name.
- -i . Ask for additional confirmation when killing the process.
- -u . Only kill processes owned by a specific user.
- -v . Report back on whether the process has been successfully killed.
In addition to killing processes based on name, the killall command can also be used to kill based on the age of the process, using the following commands:
- -o . Use this flag with a duration to kill all processes that have been running more than that amount of time.
- -y . Use this flag with a duration to kill all processes that have been running less than that amount of time.
The killall -o 15m command will kill all processes that are older than 15 minutes, while the killall -y 15m command will kill all processes that are less than 15 minutes.
pkill Command
The pkill command is similar to the pgrep command, in that it will kill a process based on the process name, in addition to other qualifying factors. By default, pkill will send the SIGTERM signal.
pkill options include:
- -n . Only kill the newest of the processes that are discovered.
- -o . Only kill the oldest of the processes that are discovered.
- -u . Only kill the processes that are owned by the selected user.
- -x . Only kill the processes that match the pattern exactly.
- -signal . Send a specific signal to the process, rather than SIGTERM.
kill Command
If you know a process ID, you can kill it with the command:
The kill command will kill a single process at a time with the given process ID. It will send a SIGTERM signal indicating to a process to stop. It waits for the program to run its shutdown routine.
The -signal command can be used to specify a signal that isn’t SIGTERM.
kill -9 Linux Command
kill -9 is a useful command when you need to shut down an unresponsive service. Run it similarly as a regular kill command:
The kill -9 command sends a SIGKILL signal indicating to a service to shut down immediately. An unresponsive program will ignore a kill command, but it will shut down whenever a kill -9 command is issued. Use this command with caution. It bypasses the standard shutdown routine so any unsaved data will be lost.
Your operating system is not running properly if a SIGKILL signal does not shut down a service.
top Command
The top command provides an interface through which a user can navigate through currently running processes.
To kill a specific process, insert k from the top interface and then enter in the desired process ID.

xkill command
The xkill command is a special type of command that closes a given server’s connection to clients.
If a server has opened a number of unwanted processes, xkill will abort these processes.
If xkill is run without specifying a resource, then an interface will open up that lets the user select a window to close.
Key Takeaways on Terminating a Linux Process
- When a process cannot be closed any other way, it can be manually killed via command line.
- To kill a process in Linux, you must first find the process. You can use the top , ps , pidof or pgrep commands.
- Once you have found the process you want to kill, you can kill it with the killall , pkill , kill , xkill or top commands.
- When killing a process, you can send a termination signal of SIGHUP, SIGKILL, or SIGTERM.
- You need to have permission to kill a process, which you can gain through the use of the sudo command.
Note: Learn how to use the nohup command to block the SIGHUP signal and allow processes to complete even after logging out from the terminal/shell.
In this article, we covered several ways to kill processes in Linux. It is critical to learn and understand these Linux termination commands for system management and administration.
Classic SysAdmin: How to Kill a Process from the Linux Command Line
This is a classic article written by Jack Wallen from the Linux.com archives. For more great SysAdmin tips and techniques check out our free intro to Linux course.
Picture this: You’ve launched an application (be it from your favorite desktop menu or from the command line) and you start using that launched app, only to have it lock up on you, stop performing, or unexpectedly die. You try to run the app again, but it turns out the original never truly shut down completely.
What do you do? You kill the process. But how? Believe it or not, your best bet most often lies within the command line. Thankfully, Linux has every tool necessary to empower you, the user, to kill an errant process. However, before you immediately launch that command to kill the process, you first have to know what the process is. How do you take care of this layered task? It’s actually quite simple…once you know the tools at your disposal.
Let me introduce you to said tools.
The steps I’m going to outline will work on almost every Linux distribution, whether it is a desktop or a server. I will be dealing strictly with the command line, so open up your terminal and prepare to type.
Locating the process
The first step in killing the unresponsive process is locating it. There are two commands I use to locate a process: top and ps. Top is a tool every administrator should get to know. With top, you get a full listing of currently running process. From the command line, issue top to see a list of your running processes (Figure 1).
Figure 1: The top command gives you plenty of information.
From this list you will see some rather important information. Say, for example, Chrome has become unresponsive. According to our top display, we can discern there are four instances of chrome running with Process IDs (PID) 3827, 3919, 10764, and 11679. This information will be important to have with one particular method of killing the process.
Although top is incredibly handy, it’s not always the most efficient means of getting the information you need. Let’s say you know the Chrome process is what you need to kill, and you don’t want to have to glance through the real-time information offered by top. For that, you can make use of the ps command and filter the output through grep. The ps command reports a snapshot of a current process and grep prints lines matching a pattern. The reason why we filter ps through grep is simple: If you issue the ps command by itself, you will get a snapshot listing of all current processes. We only want the listing associated with Chrome. So this command would look like:
The aux options are as follows:
a = show processes for all users
u = display the process’s user/owner
x = also show processes not attached to a terminal
The x option is important when you’re hunting for information regarding a graphical application.
When you issue the command above, you’ll be given more information than you need (Figure 2) for the killing of a process, but it is sometimes more efficient than using top.
Figure 2: Locating the necessary information with the ps command.
Killing the process
Now we come to the task of killing the process. We have two pieces of information that will help us kill the errant process:
- Process name
- Process ID
Which you use will determine the command used for termination. There are two commands used to kill a process:
- kill – Kill a process by ID
- killall – Kill a process by name
There are also different signals that can be sent to both kill commands. What signal you send will be determined by what results you want from the kill command. For instance, you can send the HUP (hang up) signal to the kill command, which will effectively restart the process. This is always a wise choice when you need the process to immediately restart (such as in the case of a daemon). You can get a list of all the signals that can be sent to the kill command by issuing kill -l. You’ll find quite a large number of signals (Figure 3).
Figure 3: The available kill signals.
Завершение процессов в Linux

Каждая программа, утилита или какой-то другой элемент операционной системы Linux реализовывается в виде одного или нескольких процессов, которые функционируют в фоновом либо активном режиме. Каждый такой процесс потребляет определенное количество системных ресурсов и действует отведенный промежуток времени. Иногда случаются ситуации, требующие немедленного завершения («убийства») такой операции, что связано с ненадобностью ее выполнения или возникновением ошибок. В рамках сегодняшней статьи мы хотим поговорить о методах осуществления этой задачи.
Типы сигналов для завершения процессов
Для начала затронем тему алгоритмов завершения процессов в дистрибутивах, основанных на Linux. Действие системных средств зависит от посылаемых сигналов, которые имеют разные значения и заставляют выполнять определенную последовательность задач. Ниже будут представлены способы, где можно указывать тип сигнала для «убийства» операции, поэтому мы рекомендуем изучить их все, чтобы разобраться в правильности применения.
- SIGINT — стандартный сигнал, использующийся и в графических оболочках. При его отправлении процесс сохраняет все изменения, завершает выполняемые действия и только потом отключается. Если вы работаете через «Терминал», используйте комбинацию клавиш Ctrl + C, чтобы быстро «убить» текущий процесс.
- SIGQUIT — практически не отличается от предыдущего сигнала, но при его отправке программа уже сама решает, стоит ли завершать работу. При этом создается дамп памяти, что может быть полезно определенным пользователям. Это второй и последний сигнал, который можно послать сочетанием клавиш при взаимодействии с «Терминалом». Для этого используется комбинация Ctrl + /.
- SIGHUP — используется для разрыва связи с «Терминалом». Рекомендуется задействовать этот сигнал, если требуется прервать соединение с интернетом.
- SIGTERM — сразу же удаляет процесс, но его дочерние опции продолжают выполняться до полного завершения операций, а после производится освобождение системных ресурсов.
- SIGKILL — аналогичный предыдущему сигнал, но при этом оставшиеся дочерние задачи не прекращают свое функционирование.
Теперь вы знаете обо всех доступных сигналах, использующихся при «убийстве» процессов в разных дистрибутивах Linux. Используйте их вместе с приведенными в методах ниже командами в качестве аргумента.
Завершаем процессы в Linux
Существуют разные системные средства, позволяющие «убить» какой-либо процесс. Иногда для этого приходится узнавать его идентификатор, а в других ситуациях достаточно только названия. Далее мы предлагаем детально изучить все представленные методы, чтобы найти оптимальный для себя и выполнять его при необходимости, учитывая описанные ранее сигналы.
Способ 1: «Системный монитор»
Начнем с самого простого, но менее вариативного метода, который осуществляется через программу графического интерфейса и будет полезен тем пользователям, кто просто хочет завершить процесс, не прибегая при этом к запуску терминальных команд. Рассмотрим эту операцию на стандартной оболочке дистрибутива Ubuntu.

-
Перейдите в меню «Показать приложения», где отыщите «Системный монитор» и запустите его, кликнув по значку левой кнопкой мыши.
В преимущественном большинстве графических оболочек системный монитор реализован похожим образом, поэтому каких-то проблем с пониманием интерфейса возникнуть не должно.
Способ 2: Команда kill
Для применения команды kill потребуется знание PID (идентификатора процесса), поскольку именно так осуществляется применение аргументов. В статье ниже мы детально описали операцию просмотра списка процессов для получения различной информации. Обязательно ознакомьтесь с ней перед выполнением следующей инструкции.

Далее остается только запустить «Терминал» и задействовать упомянутую команду. Для начала изучите ее простой синтаксис: kill -сигнал pid_процесса . Теперь давайте рассмотрим пример «убийства».
- Откройте меню приложений и запустите «Терминал».

- Введите простую команду ps aux | grep name для получения информации об указанном процессе, где name — имя желаемой программы.

- В отобразившемся результате отыщите главный PID и запомните его.

- Введите kill PID для завершения процесса через сигнал SIGTERM. Вместо PID вам нужно написать определенный ранее номер идентификатора.

- Теперь вы можете снова использовать ps aux | grep name , чтобы проверить, была ли завершена операция.

- То же самое действие по «убийству» осуществляется и через другой аргумент путем ввода kill -TERM .

- Если приведенные выше команды не принесли никакого результата, потребуется обозначить сигнал SIGKILL, вставив команду kill -KILL .

Учтите, что некоторые процессы запускаются от имени суперпользователя, соответственно, для их завершения требуются привилегии. Если при попытке ввода kill вы получаете информацию «Отказано в доступе», вводите перед основной командой sudo, чтобы получилось sudo kill .
Способ 3: Команда pkill
Следующая консольная утилита называется pkill и является модернизированной версией предыдущей команды. Здесь все реализовано точно по такому же образу, но вместо PID от пользователя требуется вводить название процесса.
- Для отправки сигнала SIGTERM используйте pkill + название процесса .

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

- Задайте вручную тип сигнала, введя такую форму pkill -TERM ping , где -TERM — необходимый сигнал.

- Используйте pgrep для определения того, что процесс больше не выполняется, если вы не хотите задействовать ps

Способ 4: Команда killall
В качестве последнего способа мы рассмотрим команду под названием killall. Ее функционирование и синтаксис выглядят точно так же, как у всех предыдущих утилит, поэтому останавливаться на этом мы не будем. Только уточним, что эта команда позволяет завершить все процессы с указанным названием разом и может быть использована в разных случаях.

Теперь вы знаете все о завершении процессов в Linux. Перед выполнением методов убедитесь, что принудительное «убийство» не приведет к системным сбоям. Если же ни один вариант не позволил полностью избавиться от процесса, попробуйте просто перезагрузить компьютер или удалить софт, связанный с этой опцией.