Working With Background Processes in Linux Bash

In Linux, you can manage processes in the background using various commands and keyboard shortcuts. This article will walk you through how to list, stop, start, and bring background processes to the foreground, as well as how to kill running processes.

Listing Processes

To list the processes running on your system, you can use the ps command. Here’s the basic syntax:

1
ps

This will display a list of processes along with their respective process IDs (PIDs), terminal IDs, and other information.

Managing Background Processes

Starting a Background Process

To start a process in the background, you can simply append an ampersand (&) to the command. For example, to run a script called myscript.sh in the background:

1
./myscript.sh &

Viewing Background Jobs

You can view the currently running background jobs using the jobs command:

1
jobs

This will display a list of background jobs along with their job numbers.

Stopping a Process

You can stop a running process and move it to the background by pressing Ctrl + Z. This will suspend the process and give you back control of the terminal.

Resuming a Background Process

To resume a background process and bring it to the foreground, you can use the fg command followed by the job number. For example, to bring job number 1 to the foreground:

1
fg %1

Backgrounding a Suspended Process

If you have a suspended process and want to send it to the background, you can use the bg command followed by the job number. For example, to background job number 1:

1
bg %1

Killing a Process

To terminate a running process, you can use the kill command followed by the PID of the process you want to kill. For example, to kill a process with PID 12345:

1
kill 12345

If you have a background job and want to kill it, you can use the kill command with the job number. For example, to kill job number 2:

1
kill %2

Remember that the kill command sends a signal to the process, and different signals can have different effects on the process. The default signal sent by kill is SIGTERM, which asks the process to terminate gracefully. If a process doesn’t respond to SIGTERM, you can send a more forceful SIGKILL signal:

1
kill -9 12345  # Sending SIGKILL to process with PID 12345

These are the basic commands and shortcuts for managing background processes in a Linux Bash terminal. With these, you can effectively list, control, and manipulate processes to suit your needs.

0%