- 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
- bg: перемещение задачи в фон
- Как сразу приступить к выполнению команды в фоне
- jobs: команда для проверки задач в текущем терминале
- kill% n: прекращение выполнения задания с идентификатором n
- fg: команда для перемещения задачи в интерактивный режим
- Команда ps позволяет увидеть все процессы
- Выводы
- How To Use Bash’s Job Control to Manage Foreground and Background Processes
- Introduction
- Prerequisites
- Managing Foreground Processes
- Starting a Process
- Terminating a Process
- Suspending Processes
- Managing Background Processes
- Starting Processes
- Listing Background Processes
- Stopping Background Processes
- Changing Process States
- Moving Foreground Processes to the Background
- Moving Background Processes to the Foreground
- Dealing with SIGHUPs
- Using nohup
- Using disown
- Using the huponexit Shell Option
- Conclusion
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
Если вы только начинаете работать с 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 Use Bash’s Job Control to Manage Foreground and Background Processes
Last Validated on September 24, 2021 Originally Published on October 5, 2015
Introduction
In a previous tutorial, we discussed how the ps , kill , and nice commands can be used to control processes on your system. This guide highlights how bash , the Linux system, and your terminal come together to offer process and job control.
This article will focus on managing foreground and background processes and will demonstrate how to leverage your shell’s job control functions to gain more flexibility in how you run commands.
Prerequisites
To follow along with this guide, you will need access to a computer running the bash shell interface. bash is the default shell on many Linux-based operating systems, and it is available on many Unix-like operating systems, including macOS. Note that this tutorial was validated using a Linux virtual private server running Ubuntu 20.04.
If you plan to use a remote server to follow this guide, we encourage you to first complete our Initial Server Setup guide. Doing so will set you up with a secure server environment — including a non-root user with sudo privileges and a firewall configured with UFW — which you can use to build your Linux skills.
Alternatively, you can use an interactive terminal embedded on this page to experiment with the sample commands in this tutorial. Click the following Launch an Interactive Terminal! button to open a terminal window and begin working with a Linux (Ubuntu) environment.
Managing Foreground Processes
Most processes that you start on a Linux machine will run in the foreground. The command will begin execution, blocking use of the shell for the duration of the process. The process may allow user interaction or may just run through a procedure and then exit. Any output will be displayed in the terminal window by default. We’ll discuss the basic way to manage foreground processes in the following subsections.
Starting a Process
By default, processes are started in the foreground. This means that until the program exits or changes state, you will not be able to interact with the shell.
Some foreground commands exit very quickly and return you to a shell prompt almost immediately. For instance, the following command will print Hello World to the terminal and then return you to your command prompt:
Other foreground commands take longer to execute, blocking shell access for their duration. This might be because the command is performing a more extensive operation or because it is configured to run until it is explicitly stopped or until it receives other user input.
A command that runs indefinitely is the top utility. After starting, it will continue to run and update its display until the user terminates the process:
You can quit top by pressing q , but some other processes don’t have a dedicated quit function. To stop those, you’ll have to use another method.
Terminating a Process
Suppose you start a simple bash loop on the command line. As an example, the following command will start a loop that prints Hello World every ten seconds. This loop will continue forever, until explicitly terminated:
Unlike top , loops like this have no “quit” key. You will have to stop the process by sending it a signal. In Linux, the kernel can send signals to running processes as a request that they exit or change states. Linux terminals are usually configured to send the “SIGINT” signal (short for “signal interrupt”) to current foreground process when the user presses the CTRL + C key combination. The SIGINT signal tells the program that the user has requested termination using the keyboard.
To stop the loop you’ve started, hold the CTRL key and press the C key:
The loop will exit, returning control to the shell.
The SIGINT signal sent by the CTRL + C combination is one of many signals that can be sent to programs. Most signals do not have keyboard combinations associated with them and must instead be sent using the kill command, which will be covered later on in this guide.
Suspending Processes
As mentioned previously, foreground process will block access to the shell for the duration of their execution. What if you start a process in the foreground, but then realize that you need access to the terminal?
Another signal that you can send is the “SIGTSTP” signal. SIGTSTP is short for “signal terminal stop”, and is usually represented as signal number 20. When you press CTRL + Z , your terminal registers a “suspend” command, which then sends the SIGTSTP signal to the foreground process. Essentially, this will pause the execution of the command and return control to the terminal.
To illustrate, use ping to connect to google.com every 5 seconds. The following command precedes the ping command with command , which will allow you to bypass any shell aliases that artificially set a maximum count on the command:
Instead of terminating the command with CTRL + C , press CTRL + Z instead. Doing so will return output like this:
The ping command has been temporarily stopped, giving you access to a shell prompt again. You can use the ps process tool to show this:
This output indicates that the ping process is still listed, but that the “STAT” column has a “T” in it. Per the ps man page, this means that a job that has been “stopped by [a] job control signal”.
This guide will outline how to change process states in greater depth, but for now you can resume execution of the command in the foreground again by typing:
Once the process has resumed, terminate it with CTRL + C :
Managing Background Processes
The main alternative to running a process in the foreground is to allow it to execute in the background. A background process is associated with the specific terminal that started it, but does not block access to the shell. Instead, it executes in the background, leaving the user able to interact with the system while the command runs.
Because of the way that a foreground process interacts with its terminal, there can be only a single foreground process for every terminal window. Because background processes return control to the shell immediately without waiting for the process to complete, many background processes can run at the same time.
Starting Processes
You can start a background process by appending an ampersand character ( & ) to the end of your commands. This tells the shell not to wait for the process to complete, but instead to begin execution and to immediately return the user to a prompt. The output of the command will still display in the terminal (unless redirected), but you can type additional commands as the background process continues.
For instance, you can start the same ping process from the previous section in the background by typing:
The bash job control system will return output like this:
You’ll then receive the normal output from the ping command:
However, you can also type commands at the same time. The background process’s output will be mixed among the input and output of your foreground processes, but it will not interfere with the execution of the foreground processes.
Listing Background Processes
To list all stopped or backgrounded processes, you can use the jobs command:
If you still have the previous ping command running in the background, the jobs command’s output will be similar to this:
This indicates that you currently have a single background process running. The [1] represents the command’s job spec or job number. You can reference this with other job and process control commands, like kill , fg , and bg by preceding the job number with a percentage sign. In this case, you’d reference this job as %1 .
Stopping Background Processes
You can stop the current background process in a few ways. The most straightforward way is to use the kill command with the associated job number. For instance, you can kill your running background process by typing:
Depending on how your terminal is configured, either immediately or the next time you hit ENTER , the job termination status will appear in your output:
If you check the jobs command again, there won’t be any current jobs.
Changing Process States
Now that you know how to start and stop processes in the background, you can learn about changing their state.
This guide already outlined one way to change a process’s state: stopping or suspending a process with CTRL + Z . When processes are in this stopped state, you can move a foreground process to the background or vice versa.
Moving Foreground Processes to the Background
If you forget to end a command with & when you start it, you can still move the process to the background.
The first step is to stop the process with CTRL + Z again. Once the process is stopped, you can use the bg command to start it again in the background:
You will receive the job status line again, this time with the ampersand appended:
By default, the bg command operates on the most recently-stopped process. If you’ve stopped multiple processes in a row without starting them again, you can reference a specific process by its job number to move the correct process to the background.
Note that not all commands can be backgrounded. Some processes will automatically terminate if they detect that they have been started with their standard input and output directly connected to an active terminal.
Moving Background Processes to the Foreground
You can also move background processes to the foreground by typing fg :
This operates on your most recently backgrounded process (indicated by the + in the jobs command’s output). It immediately suspends the process and puts it into the foreground. To specify a different job, use its job number:
Once a job is in the foreground, you can kill it with CTRL + C , let it complete, or suspend and move it to the background again.
Dealing with SIGHUPs
Whether a process is in the background or in the foreground, it is rather tightly tied with the terminal instance that started it. When a terminal closes, it typically sends a SIGHUP signal to all of the processes (foreground, background, or stopped) that are tied to the terminal. This signals for the processes to terminate because their controlling terminal will shortly be unavailable.
There may be times, though, when you want to close a terminal but keep the background processes running. There are a number of ways of accomplishing this. One of the more flexible ways is to use a terminal multiplexer like screen or tmux . Another solution is to use a utility that provides the detach functionality of screen and tmux , like dtach .
However, this isn’t always an option. Sometimes these programs aren’t available or you’ve already started the process you need to continue running. Sometimes these could even be overkill for what you need to accomplish.
Using nohup
If you know when starting the process that you will want to close the terminal before the process completes, you can start it using the nohup command. This makes the started process immune to the SIGHUP signal. It will continue running when the terminal closes and will be reassigned as a child of the init system:
This will return a line like the following, indicating that the output of the command will be written to a file called nohup.out :
This file will be placed in your current working directory if writeable, but otherwise it will be placed in your home directory. This is to ensure that output is not lost if the terminal window is closed.
If you close the terminal window and open another one, the process will still be running. You will not find it in the output of the jobs command because each terminal instance maintains its own independent job queue. Closing the terminal will cause the ping job to be destroyed even though the ping process is still running.
To kill the ping process, you’ll have to find its process ID (or “PID”). You can do that with the pgrep command (there is also a pkill command, but this two-part method ensures that you are only killing the intended process). Use pgrep and the -a flag to search for the executable:
You can then kill the process by referencing the returned PID, which is the number in the first column:
You may wish to remove the nohup.out file if you don’t need it anymore.
Using disown
The nohup command is helpful, but only if you know you will need it at the time you start the process. The bash job control system provides other methods of achieving similar results with the built-in disown command.
The disown command, in its default configuration, removes a job from the jobs queue of a terminal. This means that it can no longer be managed using the job control mechanisms discussed previously in this guide, like fg , bg , CTRL + Z , CTRL + C . Instead, the job will immediately be removed from the list in the jobs output and no longer associated with the terminal.
The command is called by specifying a job number. For instance, to immediately disown job 2, you could type:
This leaves the process in a state not unlike that of a nohup process after the controlling terminal has been closed. The exception is that any output will be lost when the controlling terminal closes if it is not being redirected to a file.
Usually, you don’t want to remove the process completely from job control if you aren’t immediately closing your terminal window. You can pass the -h flag to the disown process instead in order to mark the process to ignore SIGHUP signals, but to otherwise continue on as a regular job:
In this state, you could use normal job control mechanisms to continue controlling the process until closing the terminal. Upon closing the terminal, you will, once again, be stuck with a process with nowhere to output if you didn’t redirect to a file when starting it.
To work around that, you can try to redirect the output of your process after it is already running. This is outside the scope of this guide, but this post provides an explanation of how you could do that.
Using the huponexit Shell Option
bash has another way of avoiding the SIGHUP problem for child processes. The huponexit shell option controls whether bash will send its child processes the SIGHUP signal when it exits.
Note: The huponexit option only affects the SIGHUP behavior when a shell session termination is initiated from within the shell itself. Some examples of when this applies are when the exit command or CTRL + D is pressed within the session.
When a shell session is ended through the terminal program itself (through closing the window, etc.), the command huponexit will have no affect. Instead of bash deciding on whether to send the SIGHUP signal, the terminal itself will send the SIGHUP signal to bash , which will then correctly propagate the signal to its child processes.
Despite the aforementioned caveats, the huponexit option is perhaps one of the easiest to manage. You can determine whether this feature is on or off by typing:
To turn it on, type:
Now, if you exit your session by typing exit , your processes will all continue to run:
This has the same caveats about program output as the last option, so make sure you have redirected your processes’ output prior to closing your terminal if this is important.
Conclusion
Learning job control and how to manage foreground and background processes will give you greater flexibility when running programs on the command line. Instead of having to open up many terminal windows or SSH sessions, you can often get by with stopping processes early or moving them to the background as needed.
Источник