- Как управлять фоновыми процессами в Linux
- bg: перемещение задачи в фон
- Как сразу приступить к выполнению команды в фоне
- jobs: команда для проверки задач в текущем терминале
- kill% n: прекращение выполнения задания с идентификатором n
- fg: команда для перемещения задачи в интерактивный режим
- Команда ps позволяет увидеть все процессы
- Выводы
- Multitasking: Background Process and Foreground Process
- Manually control how shell processes execute
- Foreground Processes
- Background Process
- Switching Between Processes
- Running Linux Commands in Background and Foreground
- Start a Linux process in background directly
- Send a running Linux process to background
- See all processes running in background
- Bring a Process to Foreground in Linux
- Linux Cli: Background and Foreground Process
- Linux Background and Foreground Process
- Background process
- List background jobs
- Foreground process
- Switch between foreground to background
Как управлять фоновыми процессами в 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 — для вывода списка активных и запущенных процессов.
Мы также научились запускать задачи в фоне, добавив к команде знак &.
Источник
Multitasking: Background Process and Foreground Process
Manually control how shell processes execute
As a multitasking operating system, Linux supports the execution of many processes—basically, programs or commands or similar tasks—in the background while you continue to work in the foreground.
Foreground Processes
A foreground process is any command or task you run directly and wait for it to complete. Some foreground processes show some type of user interface that supports ongoing user interaction, whereas others execute a task and «freeze» the computer while it completes that task.
From the shell, a foreground process begins by typing a command at the prompt. For example, to see a simple listing of the files in the active directory, type:
You’ll see the list of files. While the computer is preparing and printing that list, you cannot do anything else from the command prompt. After the list of files prints to standard output, you regain access to the shell prompt.
Background Process
Unlike with a foreground process, the shell does not have to wait for a background process to end before it can run more processes. Within the limit of the amount of memory available, you can enter many background commands one after another. To run a command as a background process, type the command and add a space and an ampersand to the end of the command. For example:
When you issue a command with the concluding ampersand, the shell executes the work, but instead of making you wait for the command to finish, you’ll immediately be returned to the shell. At this point, you can enter another command for either foreground or background process. Background jobs are run at a lower priority to the foreground jobs.
You will see a message on the screen when a background process finishes.
Switching Between Processes
If a foreground process is taking too much time, stop it by pressing Ctrl+Z. A stopped job still exists, but its execution is suspended. To resume the job, but in the background, type bg to send the stopped job to background execution.
To resume a suspended process in the foreground, type fg and that process will take over the active session.
To see a list of all suspended processes, use the jobs command, or use the top command to show a list of the most CPU-intensive tasks so that you can suspend or stop them to free up system resources. To change the execution priority of a process, use nice and renice.
Источник
Running Linux Commands in Background and Foreground
If you have a long-running task, it’s not always wise to wait for it to finish. I mean why keep the terminal occupied for a particular command? In Linux, you can send a command or process to background so that the command would be running but the terminal will be free for you to run other commands.
In this tutorial, I’ll show you a couple of ways to send a process in background. I’ll also show you how to bring the background processes back to foreground.
Start a Linux process in background directly
If you know that the command or process is going to take a long time, it would be a better idea to start the command in background itself.
To run a Linux command in background, all you have to do is to add ampersand (&) at the end of the command, like this:
Let’s take a simple bash sleep command and send it to background.
When the command finishes in the background, you should see information about that on the terminal.
Send a running Linux process to background
If you already ran a program and then realized that you should have run it in background, don’t worry. You can send a running process to background as well.
What you have to do here is to use Ctrl+Z to suspend the running process and then use ‘bg‘ (short for background) to send the process in background. The suspended process will now run in background.
Let’s take the same example as before.
See all processes running in background
Now that you know how to send the processes in background, you might be interested in knowing which commands are running in the background.
For this purpose, you can enter this command in the terminal:
Let’s put some commands in the background first.
Now the jobs command will show you all the running jobs/processes/commands in the background like this:
Do you notice the numbers [1], [2] and [3] etc? These are the job ids. You would also notice the – and + sign on two of the commands. The + sign indicates the last job you have run or foregrounded. The – sign indicates the second last job that you ran or foregrounded.
Bring a Process to Foreground in Linux
Alright! So you learned to run commands in background in Linux. But what about bringing a process running in the background to foreground again?
To send the command to background, you used ‘bg’. To bring background process back, use the command ‘fg’.
Now if you simply use fg, it will bring the last process in the background job queue to foreground. In our previous example, running ‘fg’ will bring Vim editor back to the terminal.
If you want to bring a certain process to the foreground, you need to specify its job id. The job id is the number you see at the beginning of each line in the output of the ‘jobs’ command.
Where n is the job id as displayed in the output of the command jobs.
That’s it
This was a quick one but enough for you to learn a few things about running commands in background in Linux. I would advise learning nohup command as well. This command lets you run commands in background even after you log out of the session.
If you have questions or suggestions, please leave a comment below.
Источник
Linux Cli: Background and Foreground Process
Linux Background and Foreground Process
So we know there is a first process named ‘init’ with pid. This is parent
of all process in the system. And a process named ‘bash’ interacts with
Kernel on behalf of user requests or commands.
Now when I log in and type ps – I get below output:
See this is different from our previous output. Everytime you login,new
parent bash is created.In case our Manager Bash job id is 5254.
You know each command is a process, right? Lets create few process
for this session.
Did it hang for 5 seconds and then provide you the bash prompt again?
The way, our bash creates child process is blocking call. It means,
run the child process and wait for it to complete and then return
to me again.
Background process
So when we ran our child process (sleep), ‘Bash’ shell waited for
it to finish. User request below commands:
Shell will run sleep 5 first and wait for it to end. Then it
runs sleep 2 . But what if job-2 in this case ‘sleep 2’ is
more critical than first job. There is unnecessary delay of
5 seconds right? Shell has an option of running child process
on background – that means it wont wait for child to finish
before accepting inputs from user.
We can put any child process in background by just appending
& character to it!
Look, we can ran sleep 2 without hanging for 5 seconds! and the
number you see 5781 is the background child process id.
Its for our reference. How to verify its indeed the pid of child?
Simple just start child process in background and execute ‘ps’ command.
Our sleep 5 pid matches with ps output. Do we have better way to visualize
this? yes do. We have a command named ‘pstree’ which will tell you the
mapping between child and parent process!!
It tells, we have Bash and one child process named ‘pstree’.run our child,
Now it says, ‘Bash’ has two child named, pstree and our background process ‘sleep’
pstree has an option to mention -p which displays pid next to process name.
the pid we got while starting background process is same as what we got
from pstree output.
Lets say we have started 4 long running background jobs each runs for 145 seconds and
1 very long process for 3000 seconds.
List background jobs
pstree gives information about all jobs. We don’t need pstree(6410), because we are
interested in only background jobs. How to view only those jobs. For this purpose, we have ‘jobs’ command will give output like:
It lists only our background processes and its status. So far good right?
Foreground process
Our process-[5] runs for 3000 seconds, it takes long time to complete.
Background will take less CPU time compared to non-background process
.ie foreground process. So lets bring to foreground process.
type, fg in our case, we need to bring background job-5.
Can you see shell hanging now? wait..hanging is a wrong word to use. shell executing
sleep command now? Are you going to wait for 3000 seconds? aka 50 minutes?
Lets admit it, by mistake without thinking, you (yes, its you !)brought this
background process to foreground, now you desperately want to put in on background again!!
Switch between foreground to background
Dont worry, Linux is so flexible we can do that too. Just press ‘ctrl+z’.You get
output which says job is stopped.
verify the status by checking output of jobs command.
Its stopped, we can restart the process again in background with ‘bg
Great, Today we learned about background and foreground process and how to move
between them. We will discuss in upcoming lessons.
Источник