- Find out what processes are running in the background on Linux
- How to find out what processes are running in the background
- How can I run a Linux process in the background?
- List your background processes
- Linux background processes list command
- Understanding ps command outputs
- Is my Linux process running in the foreground or background?
- Как управлять фоновыми процессами в Linux
- bg: перемещение задачи в фон
- Как сразу приступить к выполнению команды в фоне
- jobs: команда для проверки задач в текущем терминале
- kill% n: прекращение выполнения задания с идентификатором n
- fg: команда для перемещения задачи в интерактивный режим
- Команда ps позволяет увидеть все процессы
- Выводы
- How to Start Linux Command in Background and Detach Process in Terminal
- How to Start a Linux Process or Command in Background
- Keep Linux Processes Running After Exiting Terminal
- Detach a Linux Processes From Controlling Terminal
- If You Appreciate What We Do Here On TecMint, You Should Consider:
Find out what processes are running in the background on Linux
How to find out what processes are running in the background
- You can use the ps command to list all background process in Linux. Other Linux commands to obtain what processes are running in the background on Linux.
- top command – Display your Linux server’s resource usage and see the processes that are eating up most system resources such as memory, CPU, disk and more.
- htop command – Just like a top command but with an improved user interface.
Let us see both traditional command and modern commands examples that one can use to manage running processes in Linux.
How can I run a Linux process in the background?
To run your process or command/shell script in the background, include an & (an ampersand) at the end of the command/shell script you use to run the job. For example:
command &
/path/to/script &
sleep 10000 &
List your background processes
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
To stop the foreground process press CTRL + z . One can refers to the background process or stopped process by number. For example, vim is stopped and has 1 as number, so run the bg command to restart a stopped background process:
bg %n
bg %1
One can bring a background process to the foreground such as sleep command using the fg command:
fg %n
fg %2
Finally, kill a running process named “sleep 10000” using the kill command:
kill %n
kill %2
Linux background processes list command
Open the terminal application and issue the following ps command command to show all running process on the system including those running in the background:
$ sudo ps -aux | less
OR
# ps aux | more
List all running processes on Linux using ps command
Understanding ps command outputs
The first column shows the user name who started the foreground or background processes on Linux system. For example, the daemon user started the atd process. The process name itself displayed in the last column. The STAT coloum gives us the state of a Linux process:
Process STATE code | Description |
---|---|
D | uninterruptible sleep (usually IO) |
I | Idle kernel thread |
R | running or runnable (on run queue) |
S | interruptible sleep (waiting for an event to complete) |
T | stopped by job control signal |
t | stopped by debugger during the tracing |
W | paging (not valid since the 2.6.xx kernel) |
X | dead (should never be seen) |
Z | defunct (“zombie”) process, terminated but not reaped by its parent |
Typically process in “interruptible sleep” are running in the background and shows a “ S ” on processes STAT column. The interruptible sleep means the process can be terminated or killed with the help of kill command. On the other hand, processes in a “D” or uninterruptible sleep state are usually waiting on I/O. Therefore, you cannot kill “D” state processes as they are uninterruptible. Additional characters may be displayed as follows too:
Process STATE code | Description |
---|---|
high-priority (not nice to other users) | |
N | low-priority (nice to other users) |
L | has pages locked into memory (for real-time and custom IO) |
s | is a session leader |
l | is multi-threaded (using CLONE_THREAD, like NPTL pthreads do) |
+ | is in the foreground process group |
Is my Linux process running in the foreground or background?
Based upon the above tables, one can determine if Linux process in background or foreground or running and so on.
Command/ Process | ps STATE code | Foreground or Background? |
---|---|---|
/sbin/init | Ss | Background process (interruptible sleep and a session leader) |
/usr/sbin/rsyslogd -n | Ssl | Background process (interruptible sleep+a session leader and multi-threaded app) |
/sbin/agetty —noclear | Ss+ | Background process (interruptible sleep and a session leader and is in foreground group) |
ps aux | R+ | Running foreground process |
Use the following command to list Linux processes along with pid, user name, stat as follows:
ps -eo pid,user,stat,comm
You can combine ps with grep command command as follows:
ps -eo pid,user,stat,comm | grep nginx
Источник
Как управлять фоновыми процессами в Linux
Если вы только начинаете работать с Linux и уже пробовали вводить команды в терминале, вы могли заметить, что для ввода каждой новой команды вам приходится ждать, пока уже начатый процесс завершится. Так происходит потому, что по умолчанию при запуске команды процесс начинается в активном окне терминала, — пишет сайт hexx.in.ua в своем переводе статьи «How to manage background processes in Linux».
Что делать, когда надо запустить другую команду? Можно открыть еще одну сессию терминала, но можно обойтись и без этого. Давайте рассмотрим, как управлять фоновыми и приоритетными процессами в Linux.
Но сначала давайте разберемся, что такое фоновый и приоритетный процесс.
Приоритетный процесс — это та задача, которую в настоящее время выполняется в активном окне терминала. То есть, приоритетным в каждой сессии терминала может быть только один процесс. Прежде чем начать новый приоритетный процесс, придется подождать окончания предыдущего.
Примером может быть выполнение любой команды в текущей сессии.
Фоновый процесс — это процесс или задача, которые выполняются в фоне и не требуют взаимодействия с пользователем. Фоновых процессов может быть много.
Наиболее распространенный пример процесса, работающего в фоне, — веб-сервер.
Давайте попробуем запустить команду vmstat.
Эта команда показывает использование памяти и cpu в режиме реального времени. В качестве опции указываем 5 — это задержка перед выводом обновленных данных. Команда каждые 5 секунд будет выводить новую строку с данными, пока вы не прервете ее выполнение (пока не завершите начатый процесс). Для этого надо нажать CTL + C. А если вы хотите поставить процесс на паузу или остановить, надо нажать CTL + Z.
bg: перемещение задачи в фон
Предположим, вы хотите переместить в фон задание, выполнение которого уже началось (чтобы можно было делать в терминале что-то другое). Для этого надо нажать CTL + Z, а затем запустить команду bg (сокращение от background).
Давайте запустим выполнение какой-то приоритетной задачи. Например, будем записывать CPU-статистику в файл. Как видите, мы не можем ввести какую-то другую команду, поскольку эта задача выполняется в активном окне терминала (оно приоритетное).
Давайте поставим эту задачу на паузу, нажав CTL + Z, а затем выполним команду bg.
Теперь эта задача выполняется в фоне, а терминал свободен для введения новых команд.
Как сразу приступить к выполнению команды в фоне
Чтобы процесс запустился в фоне, после команды надо поставить знак &:
jobs: команда для проверки задач в текущем терминале
С помощью этой команды можно вывести все задачи, которые запущены в текущем терминале.
Номера в квадратных скобках [n] это номера (или идентификаторы) задач. Нумерация начинается с единицы. Знак «+» указывает на процесс, который был запущен последним, а «-» — на предпоследний процесс.
Если вы хотите увидеть идентификаторы самих процессов, надо использовать опцию -l:
Номера 10216 и 11122 — это идентификаторы процессов.
Возможные опции, которые можно использовать с командой jobs:
- -l — вывести список идентификаторов процессов в дополнение к обычной информации
- -n — перечислить только процессы, изменившие статус с последнего сообщения
- -r — ограничить вывод только запущенными задачами
- -s — ограничить вывод только остановленными задачами.
kill% n: прекращение выполнения задания с идентификатором n
Для прерывания заданий используется команда kill. Чтобы указать, какое именно задание надо прекратить выполнять, используется знак %, за которым следует номер задания.
Как видите, теперь у нас только один процесс в фоне. Причем знак «+» показывает, что это последняя из запущенных задач.
fg: команда для перемещения задачи в интерактивный режим
Чтобы переместить задачу в активное окно терминала (на передний план), используется команда fg (сокращение от foreground). По умолчанию (то есть, если не указать никаких опций), на передний план переместится процесс, который был запущен последним.
Если у вас в фоне выполняется больше одного процесса, можно указать номер задания, которое надо переместить на передний план.
Команда ps позволяет увидеть все процессы
Чтобы увидеть все активные процессы, используйте команду ps. При этом можно добавить следующие опции:
- ps ax — чтобы увидеть все процессы, недавно активные в системе. Список будет очень длинным, поэтому добавьте в конвейер less или more.
- ps T — чтобы увидеть все процессы, выполняемые в текущем терминале.
Выводы
Мы рассмотрели команды, которые позволяют управлять фоновыми и приоритетными процессами:
- bg и fg — для перемещения задач в фон и обратно, в активное окно;
- jobs — для вывода списка активных задач в текущем терминале;
- kill — для прерывания процесса;
- ps — для вывода списка активных и запущенных процессов.
Мы также научились запускать задачи в фоне, добавив к команде знак &.
Источник
How to Start Linux Command in Background and Detach Process in Terminal
In this guide, we shall bring to light a simple yet important concept in process handling in a Linux system, that is how to completely detach a process from its controlling terminal.
When a process is associated with a terminal, two problems might occur:
- your controlling terminal is filled with so much output data and error/diagnostic messages.
- in the event that the terminal is closed, the process together with its child processes will be terminated.
To deal with these two issues, you need to totally detach a process from a controlling terminal. Before we actually move to solve the problem, let us briefly cover how to run processes in the background.
How to Start a Linux Process or Command in Background
If a process is already in execution, such as the tar command example below, simply press Ctrl+Z to stop it then enter the command bg to continue with its execution in the background as a job.
You can view all your background jobs by typing jobs . However, its stdin, stdout, stderr are still joined to the terminal.
Run Linux Command in Background
You can as well run a process directly from the background using the ampersand, & sign.
Start Linux Process in Background
Take a look at the example below, although the tar command was started as a background job, an error message was still sent to the terminal meaning the process is still connected to the controlling terminal.
Linux Process Running in Background Message
Keep Linux Processes Running After Exiting Terminal
We will use disown command, it is used after the a process has been launched and put in the background, it’s work is to remove a shell job from the shell’s active list jobs, therefore you will not use fg , bg commands on that particular job anymore.
In addition, when you close the controlling terminal, the job will not hang or send a SIGHUP to any child jobs.
Let’s take a look at the below example of using diswon bash built-in function.
Keep Linux Process Running After Closing Terminal
You can also use nohup command, which also enables a process to continue running in the background when a user exits a shell.
Put Linux Process in Background After Closing Shell
Detach a Linux Processes From Controlling Terminal
Therefore, to completely detach a process from a controlling terminal, use the command format below, this is more effective for graphical user interface (GUI) applications such as firefox:
In Linux, /dev/null is a special device file which writes-off (gets rid of) all data written to it, in the command above, input is read from, and output is sent to /dev/null.
As a concluding remark, provided a process is connected to a controlling terminal, as a user, you will see several output lines of the process data as well as error messages on your terminal. Again, when you close the a controlling terminal, your process and child processes will be terminated.
Importantly, for any questions or remarks on the subject, reach us by using the comment form below.
If You Appreciate What We Do Here On TecMint, You Should Consider:
TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.
If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.
We are thankful for your never ending support.
Источник