Why the PID values are not continuous?

If we type ps -ef then we get a list of processes. Why are the PID numbers not continuous?


Solution 1:

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:

  • https://stackoverflow.com/questions/822797/about-the-pid-of-the-process

In the comments is a command to test the assigment of PIDs:

for i in {1..20}; do sh -c 'echo $$'; done

Solution 2:

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.