Bash Tutorial · Linux System Skills · Lesson 25 of 30
Bash Processes and Jobs
List processes, run commands in the background, wait for them, and stop them with signals.
Background jobs
cmd & runs a command in the background; $! is its process ID; wait waits for background jobs. In a
terminal, jobs, fg and bg manage them, and Ctrl+Z suspends the foreground job.
start=$(date +%s%N)
for task in 1 2 3; do
( sleep "1.$task"; echo "task $task done" ) &
done
wait
elapsed_ms=$(( ($(date +%s%N) - start) / 1000000 ))
(( elapsed_ms < 2000 )) && echo "all tasks finished in under 2s (one after another they'd take 3.6s)"
Output
task 1 done task 2 done task 3 done all tasks finished in under 2s (one after another they'd take 3.6s)
Run this on your computer — see “Get Started” for setup.
Processes and signals
ps auxlists processes;pgrep -f namefinds them;top/htopshow live usage.kill PIDsends SIGTERM (please stop);kill -9 PIDsends SIGKILL (stop now, no cleanup). Try TERM first.
sleep 30 &
pid=$!
kill -0 "$pid" && echo "process is running"
kill -TERM "$pid"
wait "$pid" 2>/dev/null || echo "stopped with status $? (128 + 15 = SIGTERM)"
Output
process is running stopped with status 143 (128 + 15 = SIGTERM)
Run this on your computer — see “Get Started” for setup.
Test yourself
Why try kill (SIGTERM) before kill -9?
SIGTERM is fasterSIGTERM lets the program clean up; SIGKILL stops it immediatelykill -9 doesn't work on LinuxThere is no difference
Show answer
Answer: SIGTERM lets the program clean up; SIGKILL stops it immediately