How To Use Background And Foreground Processes

Today I will be showing you how to use background and foreground processes in Linux. What is a background process? You can send processes to the background when you don’t need to interact with them right away in order to continue using your current shell. You can actually have multiple background processes at the same time and switch back and forth between them using jobs.

For the purpose of this tutorial lets create a couple infinite loop scripts that we can use as dummy background processes. You can do so by running the following directly in your shell (copy and paste the entire thing).

for a in {1..3}; do
echo "while (true); do echo 'hello '; sleep 2; done;" > ~/$a.sh
chmod +x ~/$a.sh
done;

Start A Background Process In Linux

To start a process in the background all we have to do is add an “&” to the end of our command before executing. Here is a quick example below based on the dummy scripts we created above.

~/1.sh &

Note that you will still see the output in your terminal, it will say hello over and over again using our dummy scripts. It will also give you a Process ID for the new process as soon as it starts. You can use this PID to kill the process later if you need to.

List All Background Processes In Linux

You can list all running background processes with their corresponding job ID by using the jobs command.

jobs

For example if we started all 3 of the above scripts as background tasks, we should see an output similar to the following image.

How To Use Background And Foreground Processes

Bring A Background Process To Foreground In Linux

You can bring a background process to the foreground with Linux using the fg command. If you only have a single background process then you will not need to specify your background processes job ID. However in our case we have 3 so we can specify which task we want to bring to the foreground. Here is an example of specifying which process to bring to the foreground, in our example we will use job #2.

fg 2

Thats all there is to it, I hope you liked this guide and please don’t forget to like, comment, or share using the social media buttons below. Thank you!

Leave a Reply

Protected with IP Blacklist CloudIP Blacklist Cloud