Remember to maintain security and privacy. Do not share sensitive information. Procedimento.com.br may make mistakes. Verify important information. Termo de Responsabilidade

Discover How to Manage Background Jobs in Linux

Managing background jobs is a crucial skill for any Linux system administrator or power user. Whether you are running long scripts, compiling software, or performing system maintenance, knowing how to handle jobs effectively can save you time and resources. In this article, we will explore how to manage background jobs in Linux, including starting, stopping, and resuming jobs.


Understanding Jobs in Linux


In Linux, a job is a process that is started by the shell. Jobs can be run in the foreground or background. When a job is running in the foreground, it takes over the terminal until it completes. In contrast, a background job runs independently of the terminal, allowing you to continue using the terminal for other tasks.


Starting a Background Job


To start a job in the background, you can append an ampersand (&) to the end of the command. For example:


$ long_running_command &

This will start long_running_command in the background and immediately return control to the terminal.


Listing Background Jobs


You can list all background jobs using the jobs command:


$ jobs
[1]+ Running long_running_command &

Stopping a Background Job


To stop a background job, you need to bring it to the foreground and then terminate it. First, use the fg command to bring the job to the foreground:


$ fg %1

Here, %1 refers to the job number. Once the job is in the foreground, you can stop it using Ctrl+C.


Alternatively, you can stop a background job directly using the kill command with the job's process ID (PID):


$ kill PID

You can find the PID of a job using the ps command:


$ ps aux | grep long_running_command

Suspending a Job


To suspend a running foreground job, you can use Ctrl+Z. This will stop the job and place it in the background in a suspended state. You can then use the bg command to resume it in the background:


$ bg %1

Resuming a Job


To bring a suspended or background job to the foreground, use the fg command:


$ fg %1

Example Script


Here is a simple script demonstrating how to manage background jobs:


#!/bin/bash

# Start a long-running job in the background
sleep 300 &
echo "Job started in the background."

# List all jobs
jobs

# Bring the job to the foreground
fg %1

# Suspend the job
sleep 300 &
fg %1
kill -STOP $!

# Resume the job in the background
bg %1

# Terminate the job
kill %1

Conclusion


Managing background jobs in Linux is a fundamental skill that can greatly enhance your productivity and system management capabilities. By understanding how to start, stop, and resume jobs, you can better control your system's processes and ensure efficient resource usage.


To share Download PDF