Starting process in background linux

Как запустить процесс в фоне Linux

Как правило, выполнение команд в терминале связано с одним неудобством — прежде чем приступить к вводу следующей команды, следует дождаться выполнения предыдущей. Это происходит, поскольку текущий процесс блокирует доступ к оболочке операционной системы и в таких случаях говорят, что команда выполняется на переднем плане. Что же делать, если нужно запустить несколько команд одновременно? Есть несколько решений. Первое и наиболее очевидное — открыть дополнительное окно терминала. Второе — инициировать выполнение команды в фоновом режиме.

Если какой-либо процесс происходит в фоновом режиме, это значит, что он не предусматривает взаимодействия с пользователем, следовательно, доступ к оболочке остается свободным. Прочитав эту статью, вы узнаете как запустить процесс в фоне Linux и что делать, чтобы их выполнение не прерывалось после закрытия терминала.

Как запустить процесс в фоне Linux

Для выполнения команды в фоновом режиме достаточно добавить в конце символ амперсанда (&):

В выводе терминала будут отображены порядковый номер задачи (в квадратных скобках) и идентификатор процесса:

В фоновом режиме можно одновременно запускать сразу два, три, четыре процесса и даже больше.

Работая в фоновом режиме, команда все равно продолжает выводить сообщения в терминал, из которого была запущена. Для этого она использует потоки stdout и stderr, которые можно закрыть при помощи следующего синтаксиса:

Здесь >/dev/null 2>&1 обозначает, что stdout будет перенаправлен на /dev/null, а stderr — к stdout.

Узнать состояние всех остановленных и выполняемых в фоновом режиме задач в рамках текущей сессии терминала можно при помощи утилиты jobs c использованием опции -l:

Вывод содержит порядковый номер задачи, идентификатор фонового процесса, состояние задачи и название команды, которая запустила задание.

В любое время можно вернуть процесс из фонового режима на передний план. Для этого служит команда fg:

Если в фоновом режиме выполняется несколько программ, следует также указывать номер. Например:

Для завершения фонового процесса применяют команду kill с номером программы:

Как перевести процесс в фоновый режим

Если изначально процесс был запущен обычным способом, его можно перевести в фоновый режим, выполнив следующие действия:

  1. Остановить выполнение команды, нажав комбинацию клавиш Ctrl+Z.
  2. Перевести процесс в фоновый режим при помощи команды bg.

Работа процессов в фоне

Запуск скрипта в фоне linux — это одно, но надо чтобы он ещё работал после закрытия терминала. Закрытие терминала путем нажатия на крестик в верхнем углу экрана влечет за собой завершение всех фоновых процессов. Впрочем, есть несколько способов сохранить их после того как связь с интерактивной оболочкой прервется. Первый способ — это удаление задачи из очереди заданий при помощи команды disown:

Как и в предыдущих случаях, при наличии нескольких одновременно выполняемых процессов следует указывать номер того, относительно которого будет выполнено действие:

Читайте также:  Linux копирование битых файлов

Убедиться, что задачи больше нет в списке заданий, можно, использовав уже знакомую утилиту jobs -l. А чтобы просмотреть перечень всех запущенных процессов (в том числе и отключенных) применяется команда

Второй способ сохранить запущенные процессы после прекращения работы терминала — команда nohup. Она выполняет другую команду, которая была указана в качестве аргумента, при этом игнорирует все сигналы SIGHUP (те, которые получает процесс при закрытии терминала). Для запуска команды в фоновом режиме нужно написать команду в виде:

Как видно на скриншоте, вывод команды перенаправляется в файл nohup.out. При этом после выхода из системы или закрытия терминала процесс не завершается. Существует ряд программ, которые позволяют запускать несколько интерактивных сессий одновременно. Наиболее популярные из них — Screen и Tmux.

  • Screen либо GNU Screen — это терминальный мультиплексор, который позволяет запустить один рабочий сеанс и в рамках него открыть любое количество окон (виртуальных терминалов). Процессы, запущенные в этой программе, будут выполняться, даже если их окна невидимы или программа прекратила работу.
  • Tmux — более современная альтернатива GNU Screen. Впрочем, возможности Tmux не имеют принципиальных отличий — в этой программе точно так же можно открывать множество окон в рамках одного сеанса. Задачи, запущенные в Tmux, продолжают выполняться, если терминал был закрыт.

Выводы

Чтобы запустить скрипт в фоне linux, достаточно добавить в конце знак &. При запуске команд в фоновом режиме отпадает необходимость дожидаться завершения одной команды для того, чтобы ввести другую. Если у вас возникли вопросы, обязательно задавайте их в комментариях.

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

Источник

How to Run Linux Commands in Background and Detach in Terminal

In this guide, we shall bring to light a simple yet important concept in process handling in a Linux system, which is how to completely detach a process from its controlling terminal.

When a Linux process is associated with a terminal, two problems might occur:

  1. Your controlling terminal is filled with so much output data and error/diagnostic messages.
  2. 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 in Linux.

Run Linux Command or Process 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, and stderr are still joined to the terminal.

$ tar -czf home.tar.gz . $ bg $ jobs

Run Linux Command in Background

You can as well run a Linux process in the background using the ampersand, & sign.

$ tar -czf home.tar.gz . & $ jobs

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.

$ tar -czf home.tar.gz . & $ jobs tar: ./.config/etcher: Cannot open: Permission denied 

Linux Process Running in Background Message

Keep Linux Process Running After Logout

We will use the disown command, which is used after the process has been executed and put in the background, its 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.

Читайте также:  Add linux host to zabbix

In addition, when you close the controlling terminal or log out, the job will not hang or send a SIGHUP to any child jobs.

Let’s take a look at the below example of using the diswon bash built-in function.

$ sudo rsync Templates/* /var/www/html/files/ & $ jobs $ disown -h %1 $ jobs

Keep Linux Process Running After Closing Terminal

You can also use the nohup command, which also enables a process to continue running in the background when a user exits a shell.

$ nohup tar -czf iso.tar.gz Templates/* & $ jobs

Put Linux Process in Background After Closing Shell

You might also like:

Detach a Linux Process From 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 that 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.

You might also like:

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 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.

Aaron Kili is a Linux and F.O.S.S enthusiast, an upcoming Linux SysAdmin, web developer, and currently a content creator for TecMint who loves working with computers and strongly believes in sharing knowledge.

Each tutorial at TecMint is created by a team of experienced Linux system administrators so that it meets our high-quality standards.

Parted Command in Linux

TLDR Man Pages for Linux Commands

apt-get Command Examples

Ubuntu apt-cache Commands

apt Command Examples

Funny Linux Commands

10 thoughts on “How to Run Linux Commands in Background and Detach in Terminal”

Hey, Thanks for this little Linux tip, useful for me to make my Linux commands run in the background… Reply

Without the “disown” you’ll get the following output in the source terminal after the given program is closed: “[1]+ Done firefox /dev/null” This only happens the next time something is put out to the terminal’s output stream. So, the next time command runs that writes to the output stream. To test this, run it without “disown”, close firefox, and then run “ls”. Reply

I see this is an old post but I think my question is sort of in the ballpark. what I would like to do is open the console of the process that was started with systemd with a no GUI flag. what this pertains to the Minecraft server. so I made a systemd service file and the execution command is “java -jar server.jar nogui” now once the system is up and running, I would like to open the GUI or console of the Minecraft server to issue commands without having to open a Minecraft launcher like you would play the game. I know I have done something like this in the past on other platforms but I just don’t know enough about Minecraft/java to make this happen. I am using ubuntu 18.04 and the current version of the Minecraft is 1.15.2 Reply

Читайте также:  Linux проверить версию python

How to see the jobs running in the previous session? I have submitted jobs in nohup and logged out. After logging again if i wanna see the jobs and if I wanna kill, how to do so Reply

@Bala You can run this command:
ps -fu username #replace username with your real username
OR
ps -x Reply

Источник

How can I put the current running linux process in background? [closed]

I have a command that uploads files using git to a remote server from the Linux shell and it will take many hours to finish. How can I put that running program in background? So that I can still work on shell and that process also gets completed?

The command is already running so i dont have other option. I am not sure which command to try. i didn’t wanted to break the current process so i didn’t experimented it

We should wait a more professional answer then 🙂 I meant if you had the chance to start all over again. ( The command & thing)

The accepted answerer on this question explains the three steps which needs to be taken: stackoverflow.com/questions/625409/…

You can also just open a second instance of putty and connect to the server again to get another shell. Though the solution with ctrl+z is great.

1 Answer 1

Suspend the process with CTRL+Z then use the command bg to resume it in background. For example:

sleep 60 ^Z #Suspend character shown after hitting CTRL+Z [1]+ Stopped sleep 60 #Message showing stopped process info bg #Resume current job (last job stopped) 

More about job control and bg usage in bash manual page:

JOB CONTROL
Typing the suspend character (typically ^Z, Control-Z) while a process is running causes that process to be stopped and returns control to bash. [. ] The user may then manipulate the state of this job, using the bg command to continue it in the background, [. ]. A ^Z takes effect immediately, and has the additional side effect of causing pending output and typeahead to be discarded.

bg [jobspec . ]
Resume each suspended job jobspec in the background, as if it had been started with &. If jobspec is not present, the shell’s notion of the current job is used.

To start a process where you can even kill the terminal and it still carries on running

nohup [command] [-args] > [filename] 2>&1 & 
nohup /home/edheal/myprog -arg1 -arg2 > /home/edheal/output.txt 2>&1 & 

To just ignore the output (not very wise) change the filename to /dev/null

To get the error message set to a different file change the &1 to a filename.

In addition: You can use the jobs command to see an indexed list of those backgrounded processes. And you can kill a backgrounded process by running kill %1 or kill %2 with the number being the index of the process.

Источник

Оцените статью
Adblock
detector