Background jobs: &, jobs, fg and Ctrl+Z
Run a program in the background with &, list jobs, bring one back with fg, pause it with Ctrl+Z and stop it with Ctrl+C. Practise with a pretend web server.
Some programs keep running until you stop them: a web server, a long copy, ping. While one runs in the foreground, it holds the terminal and you can't type another command.
A handy example is Python's small web server, which shares the folder you're in with other computers on your network:
cd sharepython3 -m http.server 8000It holds the terminal until you press Ctrl+C, which stops it.
& runs it in the background
Put & at the end and the program runs in the background: the prompt comes straight back. The shell prints the job's number and its PID, as in [1] 5000.
python3 -m http.server 8000 &jobs| Command or key | Does |
|---|---|
jobs | lists the jobs started from this terminal |
fg | brings a job back to the foreground (fg %2 for job 2) |
| Ctrl+Z | pauses the foreground program and gives you the prompt |
bg | lets a paused job carry on in the background |
kill %1 | stops job 1 |
Forgot the &? Press Ctrl+Z, then type bg. Same result.
Tip:Background jobs belong to this terminal: close it and they stop too.
Your turn
Share the share folder: go into it and start python3 -m http.server 8000 in the background. List your jobs, and check the server answers with curl http://localhost:8000/. Then bring it to the foreground with fg and stop it with Ctrl+C.
Your task
Share the share folder: go into it and start python3 -m http.server 8000 in the background. List your jobs, and check the server answers with curl http://localhost:8000/. Then bring it to the foreground with fg and stop it with Ctrl+C.
- Start the server in the background (not done yet)
- List your jobs (not done yet)
- Bring it back with fg, then stop it (not done yet)
The checklist ticks itself off as you work in the terminal: any way that gets the result counts.
Hints come one at a time, then one way to do it. Try each before the next.
What this lesson uses, in one place.
&- At the end of a command: run it in the background and give the prompt back
jobs- List this shell’s background and paused jobs More on jobs
fg- Bring a job to the foreground
bg- Let a paused job carry on in the background
Ctrl+Z- Pause the program in the foreground (bg or fg starts it again)
Ctrl+C- Stop the program in the foreground
kill %1- Stop job 1 (the numbers come from jobs) More on kill
Every everyday command on one page: the Linux commands cheat sheet.