If we type ps -ef then we get a list of processes. Why are the PID numbers not continuous?
- 6,071
- 5
- 27
- 41
- 183
- 1
- 12
4 Answers
On Ubuntu they are continuous. On other operating systems it might differ.
The kernel allocates PIDs in the range of (RESERVED_PIDS, PID_MAX_DEFAULT). It does so sequentially in each namespace (tasks in different namespaces can have the same IDs). In case the range is exhausted, pid assignment wraps around.
( https://stackoverflow.com/questions/3446727/how-does-linux-determine-the-next-pid )
Mind though ...
- Kernel scheduling can fork a process so it might appear to skip numbers.
- A PID will disappear when that task ends.
- PIDs are not re-used until PID_MAX_DEFAULT is reached.
- A reserverd PID is skipped.
Some topics on stackoverflow:
In the comments is a command to test the assigment of PIDs:
for i in {1..20}; do sh -c 'echo $$'; done
-
"Kernel scheduling can fork a process so it might appear to skip numbers." - the kernel can create a process while determining which process to run? That seems weird. – user253751 Jul 23 '15 at 10:26
-
It is pretty common for the scheduler to fork a process. Probably this bit: http://lxr.free-electrons.com/source/kernel/pid.c#L125 that is determing it :) – Rinzwind Jul 23 '15 at 10:43
The process IDs missing in between are already dead and their PIDs will be reused by kernel in the later processes.
The dead processes won't be shown in the process table (except for zombies), hence ps -ef will not show them.
- 90,425
- 20
- 200
- 267
Normally PID is continuous but some process will be dead just by the time you run the command ps -ef.
Also some processes may be just a subprocess of another process which is not shown in the ps -ef command. To see some expanded result and you can check the continuous PID use the pstree
pstree -p
Sample output:
├─teamviewerd(3468)─┬─{teamviewerd}(3474)
│ ├─{teamviewerd}(3475)
│ ├─{teamviewerd}(3476)
│ ├─{teamviewerd}(3477)
│ ├─{teamviewerd}(3478)
while if you run ps -ef you just see the parent process.
$ ps -ef | grep teamviewerd
root 3468 1 0 Jul15 ? 00:07:38 /opt/teamviewer9/tv_bin/teamviewerd -f
- 82,867
- 54
- 239
- 271
They are continuous. The PID are assigned in sequential order until maximum limit is reached. After this limit it will start over again from zero.
So it is just that the missing PIDs in ps -ef are of dead processes. Note that ps -ef lists only running processes.
- 859
- 6
- 12