Terminating Background Jobs
In this step, you will learn different ways to terminate background jobs when they are no longer needed. Proper job termination is important to free up system resources and maintain system performance.
Identifying Jobs for Termination
First, let's check what jobs are currently running:
jobs
You should see your background task running:
[1] + running ~/project/background_task.sh
If you want more detailed information, including the process ID (PID), use:
jobs -l
This will display output similar to:
[1] + 1456 running ~/project/background_task.sh
Note the PID (the number after the job number), as it can be used to terminate the process.
Method 1: Terminating a Job Using Its Job Number
The most straightforward way to terminate a background job is to use the kill command with the job number:
kill %1
Check if the job has been terminated:
jobs
You might see:
[1] + terminated ~/project/background_task.sh
If the job is still running (some processes may require a stronger termination signal), you can use:
kill -9 %1
The -9 flag sends a SIGKILL signal, which forcibly terminates the process without allowing it to clean up.
Method 2: Terminating a Job Using Its PID
Let's start another instance of our script in the background:
~/project/background_task.sh &
You should see output showing the job number and PID:
[1] 1567
To terminate this job using its PID, use:
kill 1567
Replace 1567 with the actual PID of your job.
Verify that the job has been terminated:
jobs
Method 3: Using the Process Name with killall
Let's start yet another instance of our script:
~/project/background_task.sh &
If you have multiple instances of the same process running, you can terminate all of them at once using the killall command:
killall background_task.sh
This command terminates all processes with the name background_task.sh.
Verify that no jobs are running:
jobs
There should be no output, indicating that all background jobs have been terminated.
Understanding Termination Signals
When using the kill command, you're sending a signal to the process. By default, kill sends the SIGTERM signal (signal 15), which asks the process to terminate gracefully. If a process doesn't respond to SIGTERM, you can use SIGKILL (signal 9) to force termination:
kill -TERM %1 ## Same as kill %1
kill -KILL %1 ## Same as kill -9 %1
Other useful signals include:
- SIGHUP (signal 1): Often used to reload configuration files
- SIGINT (signal 2): Same as pressing Ctrl+C
- SIGSTOP (signal 19): Suspends a process (can't be caught or ignored)
- SIGCONT (signal 18): Continues a stopped process
For one final demonstration, let's start our background task again and then terminate it:
~/project/background_task.sh &
jobs
kill %1
jobs
This sequence starts the job, confirms it's running, terminates it, and then verifies it's no longer running.