Process groups, sessions & job control
Explain how shells manage foreground and background jobs.
By Invicly Tech, , in Linux System Programming. About 11 minutes to read.
In short
Processes are grouped for job control: every pipeline a shell launches gets its own process group, and all groups started from one terminal belong to one session. The terminal sends signals such as SIGINT from Ctrl-C to the whole foreground group. This is how a shell can stop, resume or kill an entire pipeline at once.
Explained simply
When you run a pipeline like grep error app.log | less, the shell starts two processes. But to you it is one job. If you press Ctrl-C, you want both to stop, not just one. Process groups make this possible: the shell puts all processes of one job into the same group, and signals can be sent to the whole group at once.
A session is one level higher. It is everything started from one login or one terminal window: the shell and all its jobs. The terminal belongs to the session, and at any moment exactly one group in it is the foreground job, the one allowed to read your keyboard.
When you press Ctrl-C, the terminal does not send the signal to one process. It sends SIGINT to every process in the foreground group. The shell itself is in a different group, so it survives and shows the next prompt.
When you close the terminal or your SSH connection drops, the session loses its terminal and its processes get SIGHUP (hang up), which normally ends them. That is why long jobs started over SSH die when the Wi-Fi drops, unless you use tools like nohup, setsid or tmux.
Press Play on a diagram to walk through it one step at a time.
- Group: bash
- bash
- Foreground group: grep foo log | less
- grep
- less
- Receives Ctrl-C and Ctrl-Z
- Background group: make -j8 &
- make
- cc processes
- Stopped by SIGTTIN if it reads the terminal
- 1Session (SID 1500)
One login or terminal; leader is the shell.
- 2Controlling terminal
/dev/pts/3 belongs to this session.
- 3Process groups (jobs)
One foreground, any number in the background.
- 4Processes
Each pipeline stage is one process.
- 5Threads
Tasks inside each process.
- Ignores SIGHUP
- Same session and group
- Output goes to nohup.out
- Easy one-off fix
- New session, no terminal
- SIGHUP from the old terminal never arrives
- Redirect output yourself
- Cleanest for scripts
- Session lives on the server
- Reattach later and see output
- Best for interactive work
- Needs the tool installed
In depth
IDs and the rules for changing them
Every process has a process group ID (PGID) and a session ID (SID). The PGID is the PID of the group leader, the first process of the group; the SID is the PID of the session leader, usually the login shell. getpgrp() and getsid(0) return them, and ps -o pid,pgid,sid,tty,comm shows them.
setpgid(pid, pgid) moves a process into a group, with strict rules: you may only move yourself or one of your children, the child must not have called exec yet, and the target group must be in the same session. Because parent and child run at the same time after fork, shells call setpgid(child, child) in both the parent and the child. Whichever runs first wins, and the other call is harmless, so there is no race in which the shell hands over the terminal before the group exists.
- kill(-pgid, sig) or kill -- -PGID signals the whole group
- setsid() fails with EPERM if the caller is already a group leader
- Process groups can never move between sessions
How Ctrl-C reaches a job
Between your keyboard and the programs sits the terminal driver with its line discipline. When the ISIG setting is on, it watches the input for special characters: Ctrl-C (intr) produces SIGINT, Ctrl-\ (quit) produces SIGQUIT and Ctrl-Z (susp) produces SIGTSTP. It sends that signal to the terminal's foreground process group, which the shell set earlier with tcsetpgrp.
The shell is not in that group, so it is not hit. When the job dies or stops, the shell's waitpid returns, and the shell calls tcsetpgrp again to take the terminal back. Full-screen programs like vim switch the terminal to raw mode, turning ISIG off, so Ctrl-C reaches them as an ordinary key. stty -a shows the current settings and keys.
- Shell to Terminal driver: tcsetpgrp(fd, job_pgid)1tcsetpgrp(fd, job_pgid)
- User to Terminal driver: presses Ctrl-C2presses Ctrl-C
- Terminal driver to Job group: SIGINT to every process in the group3SIGINT to every process in the group
- Job group to Shell: processes die; waitpid returns4processes die; waitpid returns
- Shell to Terminal driver: tcsetpgrp(fd, shell_pgid): prompt again5tcsetpgrp(fd, shell_pgid): prompt again
Background jobs and terminal signals
A background job may keep running, but it must not steal your keyboard. If a process in a background group tries to read from the terminal, the driver sends SIGTTIN to its group, which stops it; the shell shows it as Stopped and you can bring it forward with fg. Writing is allowed by default; with stty tostop set, a background write sends SIGTTOU instead.
SIGTTOU is also sent when a background process calls tcsetpgrp. A shell meets this when it takes the terminal back, so interactive shells ignore SIGTTOU, SIGTTIN, SIGTSTP, SIGINT and SIGQUIT for themselves. Before exec, each child sets those signals back to SIG_DFL. This step matters, because ignored signals stay ignored across exec, and a job that ignores SIGINT cannot be stopped with Ctrl-C.
Hangups, nohup and setsid
When the terminal goes away (you close the window or SSH drops), the kernel sends SIGHUP to the session leader, the controlling process. Shells like bash pass SIGHUP on to their jobs before exiting, and when a session leader exits, the foreground group also gets SIGHUP. Another rule: if a process group becomes orphaned (no member's parent is in the same session) while some member is stopped, every member gets SIGHUP and then SIGCONT.
To survive a hangup, nohup prog sets SIGHUP to ignored and redirects output to nohup.out. disown removes a job from bash's job table so bash does not forward SIGHUP. setsid prog starts prog in a brand-new session with no controlling terminal at all, which is the cleanest option. For interactive work, tmux or screen keep the session alive on the server and let you reattach later.
- nohup ./long-task.sh > task.log 2>&1 &
- setsid -f ./long-task.sh runs it in a new session, detached
- jobs -l, fg %1, bg %1 and disown %1 manage bash jobs
Learn it in 4 short steps
About 40m each. Track them with a timer in your plan.
- 1Explain process groups and sessions~40m
- 2Set groups with setpgid and setsid~40m
- 3Hand the terminal over with tcsetpgrp~40m
- 4Trace Ctrl-C delivery to a job~40m
Key points
- setpgid puts a process into a group; shells do this for each pipeline.
- setsid starts a new session with no controlling terminal, which daemons rely on.
- tcsetpgrp tells the terminal which group is in the foreground.
- Ctrl-C sends SIGINT and Ctrl-Z sends SIGTSTP to the foreground group.
Key terms
Tap a card to flip it. 0/6 known
Examples
sleep 300 | cat &
ps -o pid,pgid,sid,tty,comm
jobs -l
fg %1 # foreground it, then press Ctrl-Z
bg %1 # continue it in the background
kill -- -PGID # a negative PID signals a whole groupBoth pipeline processes share one PGID.
How a shell runs one foreground job
This is the core of job control in C. It assumes the shell ignored SIGINT, SIGTSTP, SIGTTOU and SIGTTIN at startup. Step 1: fork. Step 2: both parent and child call setpgid so the child leads a new group, with no race. Step 3: the child restores default signal actions and execs. Step 4: the parent gives the terminal to the job and waits with WUNTRACED, so it also wakes on Ctrl-Z. Step 5: the shell takes the terminal back.
pid_t pid = fork();
if (pid < 0) { perror("fork"); return; }
if (pid == 0) {
setpgid(0, 0); /* new group led by me */
signal(SIGINT, SIG_DFL); signal(SIGTSTP, SIG_DFL);
signal(SIGTTOU, SIG_DFL); signal(SIGTTIN, SIG_DFL);
execvp(argv[0], argv); perror(argv[0]); _exit(127);
}
setpgid(pid, pid); /* same call in parent: no race */
tcsetpgrp(STDIN_FILENO, pid); /* job owns the keyboard */
int st;
while (waitpid(pid, &st, WUNTRACED) < 0 && errno == EINTR) {}
tcsetpgrp(STDIN_FILENO, getpgrp()); /* shell takes it back */
if (WIFSTOPPED(st)) printf("\n[stopped] %d\n", (int)pid);A long job that survives an SSH disconnect
You start a 2-hour backup over SSH. Step 1: start it with setsid so it gets its own session and no terminal. Step 2: redirect all output, since there is no terminal to print to. Step 3: check with ps that the SID equals the job's own PID and the TTY column shows ?, which means no controlling terminal. Step 4: log out, log back in and confirm it is still running.
setsid -f ./backup.sh > /tmp/backup.log 2>&1 < /dev/null
pgrep -f backup.sh
ps -o pid,pgid,sid,tty,stat,cmd -p "$(pgrep -f backup.sh)"
# PID PGID SID TT STAT CMD
# 51234 51234 51234 ? Ss /bin/bash ./backup.shQuick reference
- ps -o pid,pgid,sid,tty,stat,comm shows group, session and terminal
- A + in the ps STAT column means the process is in the foreground group
- kill -TERM -- -1234 signals every process in group 1234
- Ctrl-C sends SIGINT, Ctrl-\ sends SIGQUIT, Ctrl-Z sends SIGTSTP to the foreground group
- A background read from the terminal gets SIGTTIN and stops
- Call setpgid(child, child) in both parent and child to avoid a race
- setsid -f cmd starts cmd in a new session without a terminal
- stty -a shows which keys generate which signals
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Run sleep 100 | sleep 200 & and prove that both processes share one process group but have different PIDs.
- Exercise 2medium
Start a pipeline of three sleeps in the background, then kill the whole job with a single kill command using its PGID.
- Exercise 3hard
Write a C program that forks a child, puts it in a new session with setsid, and prints the child's PID, PGID and SID to prove it is the leader of both and has no terminal.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- What is the difference between a process group and a session?
- A process group is one job, such as a pipeline, that receives job-control signals together. A session is the set of all groups started from one login or terminal.
- Why do my programs die when I close the terminal?
- Closing the terminal sends SIGHUP to the session, whose default action is to terminate. Use nohup, setsid or tmux to keep them running.
- What is the difference between Ctrl-C and Ctrl-Z?
- Ctrl-C sends SIGINT, which usually ends the job. Ctrl-Z sends SIGTSTP, which pauses it so you can resume it later with fg or bg.