A process can end in two broad ways. It can exit on its own, or it can be terminated by a signal. Either way, the kernel records what happened so that the parent can find out.
Exit status
A program that exits reports a number from 0 to 255. By convention 0 means success and anything else means some kind of failure. The shell keeps the last result in $?:
$ ls /etc/hostname
/etc/hostname
$ echo $?
0
$ ls /nope
ls: cannot access '/nope': No such file or directory
$ echo $?
2The meaning of each non-zero value depends on the program, so check its manual page. In a script, exit 3 ends with status 3.
Ended by a signal
When a signal kills a command, Bash reports the status as 128 plus the signal number:
$ sleep 100
^C
$ echo $?
130SIGINT is signal 2, and 128 + 2 = 130. A process killed with SIGKILL (9) shows 137.
Waiting and zombies
When a process ends, the kernel frees its memory and closes its files, but keeps a small entry holding the PID and exit status. The parent collects it with the wait system call. This is called reaping.
Between ending and being reaped, the process is a zombie. ps shows it with state Z and often marks it <defunct>:
$ ps -eo pid,ppid,stat,comm | grep ' Z'
3012 3011 Z worker <defunct>A zombie uses no CPU and cannot be killed, because it has already ended. A few short-lived ones are normal. Many that stay around point to a bug in the parent. Fixing or ending the parent clears them.
In Bash, the wait builtin pauses until a background job finishes and returns its status:
$ sleep 2 &
[1] 3050
$ wait 3050; echo $?
0Orphans
If a parent ends first, its running children become orphans. They are not stopped. The kernel gives them a new parent, either PID 1 or a process registered as a subreaper (some service managers and session processes do this). The new parent reaps them when they finish.
Try it
Run true; echo $? and false; echo $?. Then start sleep 50, press Ctrl+C and print $?. Practise more in the processes and cron lab.
Check your understanding
How processes end
All 4 sections ยท no timer
Unlimited retries
Questions from every section are combined into one assessment. Answer them all correctly to complete the article.
Your completion saves in this browser. Sign in to sync it to your account.