Foreground and Background Processes
Foreground and Background Processes
When running commands on the command line, sometimes you may want to execute a command and have it run in the background while you continue to use the terminal for other tasks. This is known as running a process in the background. By default, when you execute a command on the command line, it runs in the foreground, meaning that the command takes over the terminal and you cannot execute other commands until the current command has finished running.
Running a Command in the Background
To run a command in the background, you can add an ampersand (&) to the end of the command. For example:
$ sleep 10 & [1] 1234
In this example, the sleep
command is executed in the background and the terminal immediately returns a prompt. The process ID (PID) of the command and its job number are displayed in brackets.
Listing Background Processes
To view a list of all background processes that are currently running, you can use the jobs
command. For example:
$ jobs [1]+ Running sleep 10 &
In this example, the jobs
command displays a list of all background processes that are currently running. The job number and status of each process are displayed.
Bringing a Background Process to the Foreground
To bring a background process to the foreground, you can use the fg
command followed by the job number. For example:
$ fg %1
In this example, the fg
command brings the background process with job number 1 to the foreground.
Sending a Process to the Background
To send a process that is currently running in the foreground to the background, you can use the bg
command followed by the job number. For example:
$ bg %1
In this example, the bg
command sends the process with job number 1 to the background.
Killing a Process
To stop a running process, you can use the kill
command followed by the PID of the process. For example:
$ kill 1234
In this example, the kill
command stops the process with PID 1234.
Summary
In this section, we learned about running commands in the background and foreground, listing background processes, bringing a background process to the foreground, sending a foreground process to the background, and killing a process. These are important concepts to understand when working with Linux and the command line.