2

I really don't know what are the advantages of running applications in the background.
Something like Application & via command line.

Why exactly do we run applications in background and when should I decide to do so?

2 Answers 2

4

Generally applications that take too long to execute and does not require user interaction are sent to background so that we can continue our work in terminal.

Jobs running in background are treated same as jobs running in foreground except that their STDOUT, STDIN and STDERR varry.

If you have a job that take too long, like file compression or backup you can send those jobs to background.

You can list the jobs that are running in background using jobs command.

$ ./job1.sh &
[1] 9747
$ ./job2.sh &
[2] 9749
$ ./job3.sh &
[3] 9751
$ jobs
[1]   Running                 ./job1.sh &
[2]-  Running                 ./job2.sh &
[3]+  Running                 ./job3.sh &

Here whenever a job is sent to background shell displays the job id and pid of the process. In case if we want the process to get back to foreground we can use fg command to bring it back.

$ fg 1
./job1.sh

But be aware that when you close the terminal (shell) SIGHUP will be sent to all background process that are spawned from the shell causing those processes to die. To prevent this you can use disown command to remove those process from the job table and thus preventing the process from getting killed.

one best way is to start the background process with nohup command so that SIGHUP signals will not kill the process and it will run safe in background.

Preventing SIGHUP to be sent to child processes (bg jobs) can also be prevented by setting huponexit option of the bash shell.

$ shopt -s huponexit

This option is set by default in latest versions of Bash, but in case if its not set, we can add this to ~/.bashrc to make it a default behaviour.

1

If you execute an application that needs - let's say 5 minutes to end, for example a copy job - the shell is blocked while the program is running, the whole 5 minutes. The copy job is then in the so called foreground process group, indicated by a + sign in ps. You may need to do some other work during that 5 minutes, but the shell is blocked.

On the other hand, when you execute the copy job in the background (cp source target &) you job executes in the background without blocking the current shell. You can continue with other things. You can bring the process back to foreground with fg if you wish.

1
  • In other words, it provides more or less the same mechanism a thread does in high level programming languages (so as not to block current thread) Commented Dec 24, 2020 at 13:37

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.