- Linux Scripts Running in the Background
- Foreground to Background
- Run Scripts in the Background
- Checking Background Jobs
- 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:
- How to Run Bash Commands in the Background in Linux
- End a Command with &
- & After a Command, Then Disown It
- & After a Command with /dev/null
- Nohup, with & and /dev/null
- Как запустить процесс в фоне Linux
- Как запустить процесс в фоне Linux
- Как перевести процесс в фоновый режим
- Работа процессов в фоне
- Выводы
Linux Scripts Running in the Background
This articles gives a brief explanation of running scripts in the background.
Foreground to Background
If you’ve started something in your session and it’s captured the session, you can move it to the background by issuing the ctrl+z bg commands.
- ctrl+z : Stops the process. It doesn’t kill it.
- bg : «bg» stands for background. This sends the current process to the background and releases your current command prompt.
It’s better to plan properly, but this is an easy way to switch from a foreground to background if you change your mind.
Run Scripts in the Background
A script can be run in the background by adding a «&» to the end of the script.
You should really decide what you want to do with any output from the script. It makes sense to either throw it away, or catch it in a logfile.
If you capture it in a log file, you can keep an eye on it by tailing the log file.
The script can still be affected by hang-up signals. You can stop this by using the nohup command. This will accept all standard output and standard error by default, but you can still use a custom log file.
Checking Background Jobs
The jobs command lists the current background jobs and their state.
You can bring a job to the foreground by issuing the fg command for the job of interest.
Once in the foreground, it’s just like any other foreground process, and keeps hold of the shell until it completes.
Источник
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.
Источник
How to Run Bash Commands in the Background in Linux
There’s nothing more annoying than running a command in your terminal and having it run for minutes, sometimes hours, and not be able to use your terminal again. Sure, you can use tabs, but that’s a clunky solution, and it’s not always optimal because you may want to see updates as you’re working. Here we show you a few different ways to run bash commands in the background in Linux.
Also read: How to Use lsof Command in Linux to List Open Files
End a Command with &
If you want to push a command into the background, using & at the end is an easy way to do that. This way, you can issue a command in the background and continue to use your terminal as it runs. It comes with a catch, though. Using & doesn’t disconnect the command away from you; it just pushes it into the background. This means that while you’re trying to use the terminal, anything the command wants to push to STDOUT or STDERR will still be printed, which may be distracting.
When the terminal session is closed, the command ends. You can also kill the command by issuing the jobs command, finding the number of the command that’s running, and killing it with the kill command. That syntax is as follows:
Using & is good if you need to push something off for a bit but don’t expect it to continue forever.
& After a Command, Then Disown It
Running a command with just & pushes it off to the back and keeps it running as long as the terminal window is open. If, however, you’re looking to keep this command running in constant, even with your terminal session ending, you can use the disown command.
To use this method, start by adding an & .
As mentioned above, using & pushes this command into the background but doesn’t detach it from your user. You can verify this by typing jobs into the terminal. It’ll show the command running in the background as we saw before.
Just type disown into the shell, and it’ll do just that. (And you can once again verify this with the jobs command.)
You can just make out the disown command in there
Now you can close your terminal and continue about your day. It’ll still keep piping things to STDOUT or STDERR , but once you exit and reopen your terminal, you won’t see anything there. You can find the command again with the top or ps commands and kill it with the kill command.
The disowned job is the second one, with the PID 16238.
& After a Command with /dev/null
Adding & after a command will push a command into the background, but as a result, the background command will continue to print messages into the terminal as you’re using it. If you’re looking to prevent this, consider redirecting the command to /dev/null .
This does not prevent the command from closing when the terminal closes. However, as mentioned above, it’s possible to use disown to disown the running command away from the user. You can also kill it in either of the methods mentioned above if you don’t want it to run anymore.
Nohup, with & and /dev/null
Unlike the previous commands, using nohup allows you to run a command in the background and keep it running. How? nohup bypasses the HUP signal (signal hang up), making it possible to run commands in the background even when the terminal is off. Combine this command with redirection to “/dev/null” (to prevent nohup from making a nohup.out file), and everything goes to the background with one command.
Also read: What Is Nohup and How Do You Use It?
Most terminal programs on Linux today have features built in to allow them to run in the background with little effort. Along with that, modern init systems (like systemd) can allow users to start programs like services at boot or whenever.
Still, some programs on Linux lack the ability to run as a daemon or integrate with modern init systems. This is a real inconvenience but is understandable, as not all developers have the skill or time to add new features.
Luckily, commands like nohup or disown are still a reality and can close the gap in moving programs like this to the background. They’re not perfect or fancy, but they get the job done when needed.
If you enjoyed this Linux article, make sure to check out some of our other Linux content, like how to connect your Google account to GNOME Shell, the best Linux distros for windows users, and LS commands you need to know.
John is a young technical professional with a passion for educating users on the best ways to use their technology. He holds technical certifications covering topics ranging from computer hardware to cybersecurity to Linux system administration.
Источник
Как запустить процесс в фоне Linux
Как правило, выполнение команд в терминале связано с одним неудобством — прежде чем приступить к вводу следующей команды, следует дождаться выполнения предыдущей. Это происходит, поскольку текущий процесс блокирует доступ к оболочке операционной системы и в таких случаях говорят, что команда выполняется на переднем плане. Что же делать, если нужно запустить несколько команд одновременно? Есть несколько решений. Первое и наиболее очевидное — открыть дополнительное окно терминала. Второе — инициировать выполнение команды в фоновом режиме.
Если какой-либо процесс происходит в фоновом режиме, это значит, что он не предусматривает взаимодействия с пользователем, следовательно, доступ к оболочке остается свободным. Прочитав эту статью, вы узнаете как запустить процесс в фоне Linux и что делать, чтобы их выполнение не прерывалось после закрытия терминала.
Как запустить процесс в фоне Linux
Для выполнения команды в фоновом режиме достаточно добавить в конце символ амперсанда (&):
В выводе терминала будут отображены порядковый номер задачи (в квадратных скобках) и идентификатор процесса:
В фоновом режиме можно одновременно запускать сразу два, три, четыре процесса и даже больше.
Работая в фоновом режиме, команда все равно продолжает выводить сообщения в терминал, из которого была запущена. Для этого она использует потоки stdout и stderr, которые можно закрыть при помощи следующего синтаксиса:
command > /dev/null 2>&1 &
Здесь >/dev/null 2>&1 обозначает, что stdout будет перенаправлен на /dev/null, а stderr — к stdout.
Узнать состояние всех остановленных и выполняемых в фоновом режиме задач в рамках текущей сессии терминала можно при помощи утилиты jobs c использованием опции -l:
Вывод содержит порядковый номер задачи, идентификатор фонового процесса, состояние задачи и название команды, которая запустила задание.
В любое время можно вернуть процесс из фонового режима на передний план. Для этого служит команда fg:
Если в фоновом режиме выполняется несколько программ, следует также указывать номер. Например:
Для завершения фонового процесса применяют команду kill с номером программы:
Как перевести процесс в фоновый режим
Если изначально процесс был запущен обычным способом, его можно перевести в фоновый режим, выполнив следующие действия:
- Остановить выполнение команды, нажав комбинацию клавиш Ctrl+Z.
- Перевести процесс в фоновый режим при помощи команды bg.
Работа процессов в фоне
Запуск скрипта в фоне linux — это одно, но надо чтобы он ещё работал после закрытия терминала. Закрытие терминала путем нажатия на крестик в верхнем углу экрана влечет за собой завершение всех фоновых процессов. Впрочем, есть несколько способов сохранить их после того как связь с интерактивной оболочкой прервется. Первый способ — это удаление задачи из очереди заданий при помощи команды disown:
Как и в предыдущих случаях, при наличии нескольких одновременно выполняемых процессов следует указывать номер того, относительно которого будет выполнено действие:
Убедиться, что задачи больше нет в списке заданий, можно, использовав уже знакомую утилиту jobs -l. А чтобы просмотреть перечень всех запущенных процессов (в том числе и отключенных) применяется команда
Второй способ сохранить запущенные процессы после прекращения работы терминала — команда nohup. Она выполняет другую команду, которая была указана в качестве аргумента, при этом игнорирует все сигналы SIGHUP (те, которые получает процесс при закрытии терминала). Для запуска команды в фоновом режиме нужно написать команду в виде:
Как видно на скриншоте, вывод команды перенаправляется в файл nohup.out. При этом после выхода из системы или закрытия терминала процесс не завершается. Существует ряд программ, которые позволяют запускать несколько интерактивных сессий одновременно. Наиболее популярные из них — Screen и Tmux.
- Screen либо GNU Screen — это терминальный мультиплексор, который позволяет запустить один рабочий сеанс и в рамках него открыть любое количество окон (виртуальных терминалов). Процессы, запущенные в этой программе, будут выполняться, даже если их окна невидимы или программа прекратила работу.
- Tmux — более современная альтернатива GNU Screen. Впрочем, возможности Tmux не имеют принципиальных отличий — в этой программе точно так же можно открывать множество окон в рамках одного сеанса. Задачи, запущенные в Tmux, продолжают выполняться, если терминал был закрыт.
Выводы
Чтобы запустить скрипт в фоне linux, достаточно добавить в конце знак &. При запуске команд в фоновом режиме отпадает необходимость дожидаться завершения одной команды для того, чтобы ввести другую. Если у вас возникли вопросы, обязательно задавайте их в комментариях.
Источник