Linux Background Management

LinuxBeginner
Practice Now

Introduction

Linux provides powerful capabilities for managing multiple processes simultaneously. One of its key features is the ability to run processes in the background, which allows you to continue using the terminal for other tasks while long-running processes execute.

In this lab, you will learn essential techniques for managing background processes in Linux systems. These skills are crucial for efficient multitasking in command-line environments and are regularly used by system administrators and developers.

By the end of this lab, you will understand how to start background processes, monitor their status, and control them effectively. These skills will help you make better use of system resources and improve your productivity when working with Linux systems.

Starting a Process in the Background

In Linux, you can run a command in the background by appending an ampersand (&) character to the end of your command. This tells the shell to run the process in the background, allowing you to continue using your terminal while the command executes.

Let's create and run a simple script that simulates a long-running process.

First, ensure you are in the project directory:

cd ~/project

Now, let's create a script file named long_running.sh using the nano text editor:

nano ~/project/long_running.sh

When the nano editor opens, enter the following code:

#!/bin/bash
echo "Starting a long process..."
sleep 600
echo "Process completed"

This script:

  1. Prints a starting message
  2. Pauses for 10 minutes (simulating a time-consuming task)
  3. Prints a completion message

To save the file in nano:

  1. Press Ctrl + O to write the file
  2. Press Enter to confirm the filename
  3. Press Ctrl + X to exit nano

Next, we need to make the script executable:

chmod +x ~/project/long_running.sh

Now, let's execute the script in the foreground first to see how it works:

./long_running.sh

You will see:

Starting a long process...

Notice that your terminal is now occupied for 15 seconds until the script completes. You cannot enter new commands during this time.

Now, let's run the same script in the background by adding an ampersand (&) at the end:

./long_running.sh &

You will see output similar to:

[1] 1234
Starting a long process...

The output shows:

  • [1] - the job number assigned by the shell
  • 1234 - the process ID (PID), which will be a different number on your system
  • The script's starting message

Even though the script is still running, your shell prompt returns immediately, allowing you to enter new commands. After 15 seconds, you'll see the completion message appear:

Process completed
[1]+  Done                    ./long_running.sh

This confirms that the background process has completed its execution.

Viewing Background Processes

After starting processes in the background, you need to know how to track them. Linux provides the jobs command to display all background processes running in your current terminal session.

Let's start multiple background processes and then view them:

## Start the first background process
./long_running.sh &

You'll see output similar to:

[1] 1234
Starting a long process...

Now start a second background process:

## Start the second background process
./long_running.sh &

You'll see output similar to:

[2] 1235
Starting a long process...

To see all your background processes (jobs), use the jobs command:

jobs

You should see output similar to:

[1]  Running                 ./long_running.sh &
[2]- Running                 ./long_running.sh &

This shows you have two background jobs running. The numbers in square brackets are job IDs that you can use to refer to specific jobs with other commands.

The jobs command supports several useful options:

  • jobs -l - displays process IDs along with job information
  • jobs -p - displays only the process IDs of the jobs

Try the -l option to see more details:

jobs -l

The output will include the process IDs:

[1]  1234 Running                 ./long_running.sh &
[2]- 1235 Running                 ./long_running.sh &

Wait for both processes to complete before moving to the next step. You'll see messages like:

Process completed
[1]+  Done                    ./long_running.sh
Process completed
[2]+  Done                    ./long_running.sh

Moving Processes Between Foreground and Background

Linux allows you to move processes between foreground and background states. This is particularly useful when:

  • You started a process in the foreground and need to use the terminal for something else
  • You want to bring a background process to the foreground to interact with it

Let's learn how to do this using the fg (foreground) and bg (background) commands, along with process suspension.

First, start our long-running script in the foreground (without the &):

./long_running.sh

You'll see:

Starting a long process...

Notice that your shell prompt doesn't return - the terminal is now occupied by this process running in the foreground.

To suspend (pause) this process and regain control of your terminal:

  1. Press Ctrl + Z

You'll see output similar to:

^Z
[1]+  Stopped                 ./long_running.sh

The process is now suspended and not running. You can confirm this with the jobs command:

jobs

Output:

[1]+  Stopped                 ./long_running.sh

To resume the suspended process in the background, use the bg command:

bg %1

The %1 refers to job number 1. You'll see:

[1]+ ./long_running.sh &

The process is now running in the background. Confirm with jobs:

jobs

Output:

[1]+  Running                 ./long_running.sh &

To bring a background process to the foreground, use the fg command:

fg %1

The process will now run in the foreground again, and your terminal will be occupied until it completes:

./long_running.sh
Process completed

After the process completes, your shell prompt will return.

Keeping Processes Running After Terminal Closes

When you run a process in the background with &, it will terminate if you close the terminal. To keep a process running even after the terminal closes, you can use the nohup command.

nohup (short for "no hang up") prevents the process from receiving the SIGHUP (hang up) signal, which is sent to processes when the terminal closes.

Let's modify our script to make it run longer:

nano ~/project/long_running.sh

Update the content to:

#!/bin/bash
echo "Starting a very long process..."
sleep 60
echo "Process completed" > ~/project/completed.txt

Save and exit nano (Ctrl+O, Enter, Ctrl+X).

Now, let's run the script with nohup:

nohup ./long_running.sh &

You'll see output similar to:

[1] 1234
nohup: ignoring input and appending output to 'nohup.out'

The script's output will not be displayed in the terminal. Instead, it's redirected to a file called nohup.out. You can check this file:

cat nohup.out

You should see:

Starting a very long process...

Even if you were to close your terminal now, the process would continue running. When it completes, it will write to both nohup.out and completed.txt.

To see processes running in background across all terminals, use the ps command:

ps aux | grep long_running.sh

You'll see something like:

labex     1234  0.0  0.0   8160   736 pts/0    S    12:34   0:00 /bin/bash ./long_running.sh
labex     1235  0.0  0.0  14428  1020 pts/0    S+   12:34   0:00 grep --color=auto long_running.sh

Wait for the process to complete (or terminate it if you wish):

## If you want to terminate the process:
kill %1

Summary

In this lab, you have learned essential techniques for managing background processes in Linux:

  1. Starting Background Processes: You learned how to start processes in the background using the & operator, allowing you to continue using your terminal while the process runs.

  2. Viewing Background Processes: You used the jobs command to view all background processes running in your current terminal session.

  3. Moving Processes Between Foreground and Background: You practiced using Ctrl+Z to suspend a process, bg to continue it in the background, and fg to bring it to the foreground.

  4. Keeping Processes Running After Terminal Closes: You used the nohup command to keep processes running even if the terminal session ends.

These skills are essential for effective multitasking in Linux environments. They allow you to run multiple processes simultaneously, make efficient use of terminal resources, maintain long-running processes without keeping terminals open, and manage process execution states.

With these techniques, you can work more efficiently and effectively in Linux command-line environments, whether you are managing servers, developing applications, or performing system administration tasks.