How To Use ps, kill, and nice to Manage Processes in Linux
A Linux server, like any modern computer, runs multiple applications. These are referred to and managed as individual processes.
While Linux will handle the low-level, behind-the-scenes management in a process’s life-cycle – i.e., startup, shutdown, memory allocation, and so on – you will need a way of interacting with the operating system to manage them from a higher level.
In this guide, you will learn some fundamental aspects of process management. Linux provides a number of standard, built-in tools for this purpose.
You will explore these ideas in a Ubuntu 20.04 environment, but any modern Linux distribution will operate in a similar way.
Step 1 – How To View Running Processes in Linux
You can see all of the processes running on your server by using the top command:
The first several lines of output provide system statistics, such as CPU/memory load and the total number of running tasks.
You can see that there is 1 running process, and 55 processes that are considered to be sleeping because they are not actively using CPU cycles.
The remainder of the displayed output shows the running processes and their usage statistics. By default, top automatically sorts these by CPU usage, so you can see the busiest processes first. top will continue running in your shell until you stop it using the standard key combination of Ctrl+C to exit a running process. This sends a kill signal, instructing the process to stop gracefully if it is able to.
An improved version of top , called htop , is available in most package repositories. On Ubuntu 20.04, you can install it with apt :
After that, the htop command will be available:
htop provides better visualization of multiple CPU threads, better awareness of color support in modern terminals, and more sorting options, among other features. Unlike top , It is not always installed by default, but can be considered a drop-in-replacement. You can exit htop by pressing Ctrl+C as with top . You can also learn more about how to use top and htop.
In the next section, you’ll learn about how to use tools to query specific processes.
Step 2 – How To Use ps to List Processes
top and htop provide a dashboard interface to view running processes similar to a graphical task manager. A dashboard interface can provide an overview, but usually does not return directly actionable output. For this, Linux provides another standard command called ps to query running processes.
Running ps without any arguments provides very little information:
This output shows all of the processes associated with the current user and terminal session. This makes sense if you are only running the bash shell and this ps command within this terminal currently.
To get a more complete picture of the processes on this system, you can run ps aux :
These options tell ps to show processes owned by all users (regardless of their terminal association) in a more human-readable format.
By making use of pipes, you can search within the output of ps aux using grep , in order to return the name of a specific process. This is useful if you believe it has crashed, or if you need to stop it for some reason.
This returns both the grep process you just ran, and the bash shell that’s currently running. It also return their total memory and CPU usage, how long they’ve been running, and in the highlighted output above, their process ID. In Linux and Unix-like systems, each process is assigned a process ID, or PID. This is how the operating system identifies and keeps track of processes.
A quick way of getting the PID of a process is with the pgrep command:
The first process spawned at boot, called init, is given the PID of “1”.
This process is then responsible for spawning every other process on the system. The later processes are given larger PID numbers.
A process’s parent is the process that was responsible for spawning it. Parent processes have a PPID, which you can see in the column headers in many process management applications, including top , htop and ps .
Any communication between the user and the operating system about processes involves translating between process names and PIDs at some point during the operation. This is why these utilities will always include the PID in their output. In the next section, you’ll learn how to use PIDs to send stop, resume, or other signals to running processes.
Step 3 – How To Send Processes Signals in Linux
All processes in Linux respond to signals. Signals are an operating system-level way of telling programs to terminate or modify their behavior.
The most common way of passing signals to a program is with the kill command. As you might expect, the default functionality of this utility is to attempt to kill a process:
This sends the TERM signal to the process. The TERM signal tells the process to please terminate. This allows the program to perform clean-up operations and exit smoothly.
If the program is misbehaving and does not exit when given the TERM signal, you can escalate the signal by passing the KILL signal:
This is a special signal that is not sent to the program.
Instead, it is given to the operating system kernel, which shuts down the process. This is used to bypass programs that ignore the signals sent to them.
Each signal has an associated number that can be passed instead of the name. For instance, You can pass “-15” instead of “-TERM”, and “-9” instead of “-KILL”.
Signals are not only used to shut down programs. They can also be used to perform other actions.
For instance, many processes that are designed to run constantly in the background (sometimes called “daemons”) will automatically restart when they are given the HUP , or hang-up signal. The Apache webserver typically operates this way.
The above command will cause Apache to reload its configuration file and resume serving content.
Note: Many background processes like this are managed through system services which provide an additional surface for interacting with them, and it is usually preferable to restart the service itself rather than sending a HUP signal directly to one running process. If you review the configuration files of various services, you may find that the various service restart hooks are designed to do exactly that – send signals to specific processes – while also providing logs and other reporting.
You can list all of the signals that are possible to send with kill with the -l flag:
Although the conventional way of sending signals is through the use of PIDs, there are also methods of doing this with regular process names.
The pkill command works in almost exactly the same way as kill , but it operates on a process name instead:
The above command is the equivalent of:
If you would like to send a signal to every instance of a certain process, you can use the killall command:
The above command will send the TERM signal to every instance of firefox running on the computer.
Step 4 – How To Adjust Process Priorities
Often, you will want to adjust which processes are given priority in a server environment.
Some processes might be considered mission critical for your situation, while others may be executed whenever there are leftover resources.
Linux controls priority through a value called niceness.
High priority tasks are considered less nice, because they don’t share resources as well. Low priority processes, on the other hand, are nice because they insist on only taking minimal resources.
When you ran top at the beginning of the article, there was a column marked “NI”. This is the nice value of the process:
Nice values can range between -19/-20 (highest priority) and 19/20 (lowest priority) depending on the system.
To run a program with a certain nice value, you can use the nice command:
This only works when beginning a new program.
To alter the nice value of a program that is already executing, you use a tool called renice :
Conclusion
Process management is a fundamental part of Linux that is useful in almost every context. Even if you aren’t performing any hands-on system administration, being able to chase down stuck processes and handle them carefully is very helpful.
Next, you may want to learn how to use netstat and du to monitor other server resources.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
Шпаргалка по основным командам Bash
Неважно кто вы, разработчик ПО, специалист по данным, менеджер ИТ-инфраструктуры или просто любитель компьютеров — вам нужно знать, как пользоваться терминалом в Linux и macOS. Но сложность в том, что необходимо запомнить слишком много команд. И если у вас нет чудо-памяти, время от времени приходится искать в Интернете ту или иную команду.
Сегодня я поделюсь с вами самыми популярным и полезными командными интерпретаторами.
Основные
Помощь
Забыли аргументы для cp ? Какая опция у команды mkdir ? Вот вам подсказка:
Конвейер
Зачастую с его помощью перенаправляют вывод одной команды на ввод другой или приписывают команду к файлу:
Фильтрация вывода
Бывает, что команда выводится слишком долго. В этом случае вы либо разделите страницу с помощью команды more или less , либо выведите строки, которые содержат специальное слово или предложение с grep :
Очистка экрана
Слишком много текста в терминале? Просто напишите clear и продолжайте работать.
Система
Информация о системе
С этими командами вы с легкостью получите все подробности о компьютере:
Работам с процессами
Следующие команды предоставляют общие сведения о всех процессах, происходящих в системе. В macOS и некоторых дистрибутивах Linux htop не установлен, поэтому перед использованием нужно установить его с помощью стандартного менеджера пакетов (для macOS — Homebrew):
Смена пользователей
При открытии терминального окна все вводимые команды выполняются под текущим пользователем. Однако зачастую приходится выполнять команды от привилегированного пользователя, поэтому важно знать, как их сменять внутри оболочки.
Копирование и вставка в буфер обмена
Вы можете скопировать и вставить текст из/в терминал, выделив их и нажав Ctrl + C или Ctrl + V. Но иногда хочется напрямую получить доступ к буферу обмена. И как вы видите ниже, это не так уж и просто, что на Linux, что на macOS.
Переменные и путь
Можно двумя способами определить переменные внутри оболочки: в реальном времени, написав в терминале соответствующую команду, или же определить их в файле .bashrc в домашний каталог, где они будут храниться вечно.
Ещё один интересный инструмент — alias (псевдоним), сокращение для длинных команд. Посмотрим, как он строится:
Для тех, кто не знает, путь (Path) – это каталоги, в которых ОС ищет файлы для исполнения. С его помощью можно запустить файл, написав лишь название, даже не нужно знать его расположение. Кроме того, в путь можно добавить папку, а также найти каталог, где находится исполняемый файл, с помощью команд:
Файлы и каталоги
Смена текущего каталога
Для перехода между каталогами файловой системы вам лишь нужно знать, как применять команду cd .
Содержимое каталога
Чтобы вывести в каталоге файлы, папки, а также их свойства, не обойтись без команды ls .
Скачать файл из Интернета
Самый простой способ скачать файл с веб-серверов — это команда wget .
Создать каталог
Если вы хотите создать папку, используйте команду mkdir .
Копирование, перемещение и удаление
Как правило, функции копирования, перемещения и удаления выполняют через файловый менеджер, но можно делать это и через терминал.
Права доступа и владельцы
Права доступа и владельца файла или каталога можно изменить с помощью команды chmod и chown .
Поиск файлов
Забыли где файл contacts.json ? Хотите вывести все PDF файлы, находящиеся в папке? С помощью команды find вы можете сделать это и многое другое.
Вычисление контрольной суммы SHA256 файла
При скачивании любой программы из Интернета, рекомендуется проверить контрольную сумму SHA, чтобы убедиться, всё ли верно скачалось. И сделать это гораздо легче через терминал:
Сжатие и распаковка TAR/ZIP файлов
Неважно, что у вас TAR или ZIP файл, вы можете распаковать его через терминал или же создать из существующих папок:
Свободное место на диске
Хотите узнать доступное место на жестком диске? Или на внешнем? Или в текущем каталоге? В этих вопросах помогает команда df .
Просмотр содержимого файла
Через терминал можно не только просматривать содержимое текстового файла, но и проводить анализы, например сортировать и менять порядок строк по содержанию, подсчитывать количество строк, слов, символов, и выделить столбцы, если это табличный файл. Рассмотрим их в действии:
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.