Linux is a multi-user and multi-task operating system. It supports more than one user and can run multiple processes simultaneously. Technically, that is not the case; the Linux kernel uses scheduling and other process management methods to assign a specific time to each process, making them appear to run simultaneously.
However, Linux allows us to perform tasks to the running processes, including background and foreground jobs.
This tutorial will discuss how to work with background processes and terminate them using various commands.
Let’s get started.
How to Run a Command in the Background
In most cases, when running a command from the Linux terminal, we wait for it to complete and exit. This functionality can be helpful for short commands or commands that require user interaction. However, in the case of processes that take a long time to complete, it can prevent you from running other commands.
Although pseudo-terminals can escape this, this becomes a problem in an sole terminal-based environment.
Use & Symbol
In Linux, one method to run a command in the background is to use the & symbol as:
The above syntax tells the shell to put whatever commands precede the ampersand in the background.
Once you put a process in the background, the shell will give you the job ID enclosed by a pair of square brackets and the PID (process ID).
Use CTRL + Z
Another method to put a process in the background is to use the CTRL + Z shortcut. Suppose we forgot to add the ampersand when running a program.
To put the said process in the background, we can press the CTRL + Z key and suspend the job. It is good to note that this does not terminate the process; it only freezes it.
To resume the process in the background, use the bg command:
As seen in the screenshot above, we run the Firefox process in the foreground, which “eats” our prompt until we terminate the process.
We freeze the process using the CTRL + Z shortcut and put it in the background using the bg command.
How to Show Running (and Stopped) Background Processes
To show the background processes, we use the jobs -l command:
The command will show both the running and stopped processes.
To bring a background process in the foreground, you use the fg command followed by %[job id]
Killing a background process is fairly straightforward; use the command pkill and the process ID, or process name as:
Using the pkill command will force terminate (-9) the processes with the process name of ping.
This guide walked through the basics of job control using foreground and background processes.