Linux command running background

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:

  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.

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.

Читайте также:  Xprog driver windows 10

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.

Источник

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

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

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

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

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

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

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

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

command > /dev/null 2>&1 &

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Читайте также:  Права доступа windows описание

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

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

Выводы

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

Источник

Linux: Start Command In Background

[donotprint]

Tutorial details
Difficulty level Easy
Root privileges No
Requirements Bash/ksh
Linux
Est. reading time 10m

[/donotprint]

Syntax

You can put a task (such as command or script) in a background by appending a & at the end of the command line. The & operator puts command in the background and free up your terminal. The command which runs in background is called a job. You can type other command while background command is running. The syntax is:

Examples

Put the ls command in the background, enter:
$ ls *.py > output.txt &
Put the following find command in a background by putting a ‘&’ at the end of the command line:

Fig.01: Linux background job in action (click to enlarge)

How do I see jobs running in the background?

Type the following command:
jobs
Sample outputs:

To see process IDs for JOB IDs in addition to the normal information pass the -l option:
jobs -l
Sample outputs:

To see process IDs only, enter:
jobs -p
Sample outputs:

How do I kill the jobs running in the background?

  • 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

How do I bring process running in the background to the foreground?

The syntax is:
%JOB-ID
OR
fg JOB-ID
First, list the current jobs with jobs command, enter:
jobs -l
Sample outputs:

To bring the job id #2 to the foreground, enter:
%2
OR use fg command:
fg 2
Sample outputs:

To send back this job in the background hit CTRL-Z i.e. while holding the CTRL key, press z key. This will suspend the current foreground job. Type the following command to send back the job in the background:
%2 &
OR use bg command:
bg
The grep command job is now running in the background.

Summary of all useful commands

Description Command
To see which jobs are still running jobs jobs
jobs -l
ps aux
To put a command / script to the background command &
/path/to/command &
/path/to/script arg1 &
To bring a background job to the foreground fg n
%n
To send a job to the background without canceling it bg n
%n &

Note: n == Job id (use jobs command to see job id)..

See also:
  • Putting jobs in background from the Linux shell scripting tutorial.
  • Command examples pages: jobs command, bg command, and fg command
  • Man pages: ksh(1)

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Источник

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 после клонирования
Оцените статью