Linux Labs

Users, permissions, and processes / Stage 11 of 13

Background jobs and the terminal

Not running Starting usually ~20 s
Leave the lesson

Step 2 of 7 · on a machine · 6 min

Background and the job number

The & sign sent the command to the background. This step covers what the shell printed after the start and where to look for the command now.

Normally the shell waits until a command finishes and only then prints the prompt: the command runs in the foreground. With & at the end of the line the command goes to the background, and the shell starts it and waits for the next one right away.

A command the shell has started and keeps track of is called a job. In the line [1] 1028, the first number is the job number and the second is the process PID. The job number is valid in this shell: every shell has a job table of its own.

jobs prints the jobs of this shell: number, state, and command. Running means the job is working. jobs -l adds each job's PID, and the shell keeps the PID of the last background command in the $! variable:

bash
jobs -l
echo $!
Note

Jobs live along with their shell. If the connection to the server drops, the shell gets a hangup signal and passes it on to its jobs, which usually end. Work that must outlive your logout is run as a service.

Check yourself 1 question

In the same terminal you start a new shell with bash and run jobs in it. What will it show about sleep 600 &?

  • Each shell has its own job table, and the new one's is empty. The sleep 600 process is still visible in ps.

  • The new shell does not touch the job: sleep 600 keeps running, and ps shows it in state S.

  • jobs reports no error: the new shell has no jobs, so it prints nothing.

Each shell has its own job table: the new shell knows nothing about sleep 600 &, although the process runs and shows up in ps. To get back to the first shell, use exit.

Key points

  • & at the end of a line runs the command in the background, and the prompt comes back at once.
  • [1] 1028 is the job number and the process PID; jobs prints this shell's jobs, and jobs -l adds their PIDs.
  • Every shell has its own job table, while ps shows the processes of the whole machine.
Ubuntu 24.04
Loading…