M21 - Background and Foreground
Background and Foreground
Understand how foreground work, background jobs, and persistent sessions differ so long-running commands do not surprise you or die unexpectedly.
- Explain the difference between foreground and background execution.
- Use basic job control on Linux.
- Recognize when a task needs more persistence than a background job alone.
Why This Matters
A long-running command can interact with your terminal in a few different ways.
If you do not understand those differences, you get common surprises:
- a command blocks your prompt
- a background job still prints over your work
- a task dies when the terminal closes
- a remote job disappears after disconnect
1. Foreground Means the Terminal Is Busy
A foreground command owns your terminal until it finishes or you interrupt it.
That is normal and often fine for short work.
Examples:
- reading a file with
less - running a script that takes a few seconds
- launching a one-off command and waiting for the result
2. Background Means You Get the Prompt Back
A background job lets the command keep running while your shell prompt returns.
Start-Process notepad
Windows often handles this by starting a separate process or window rather than by using the same job-control model as bash.
sleep 60 & jobs
The & starts the command in the background. The jobs command shows what your current shell is tracking.
On Linux, you can also pause a foreground job with Ctrl+Z, then resume it with bg, or bring it back with fg.
3. Background Is Not the Same as Persistent
This is the key distinction.
A plain background job may free your prompt, but it is still tied to the shell session that started it.
If that session ends, the job may receive a hangup signal and stop.
Important Distinction
”Runs in the background” and “survives disconnects or reboots” are not the same promise.
4. Persistence Tools
When you need work to survive a dropped session or be easier to resume, use a more suitable tool.
On Windows, that often means a scheduled task, a service, or a separately managed process rather than just leaving a console window open.
On Linux, common choices are:
nohupfor simple detached commandstmuxorscreenfor persistent terminal sessionssystemdservices for real long-lived supervised programs
The right tool depends on the kind of work:
- quick background task: job control may be enough
- long remote command:
tmuxis often better - real service that should restart: use a service manager
What to Ignore for Now
- full shell job-control internals
- service supervision policies in detail
- every Windows background-process pattern
The important thing is choosing the right level of persistence.
Before You Move On
You are ready when you can explain:
- foreground versus background
- why a background job is not automatically persistent
- when to use job control, tmux, or a service
Next, we look at performance diagnosis with the same mindset: observe first, then intervene.