Linux – Is the PID of a child process always greater than the PID of its parent on Linux

linux-kernelprocess

Let say, from kernel 2.6 onwards.

I watch all the running processes on the system.

Are the PID of the children always greater than their parents' PIDs?

Is it possible to have special cases of "inversion"?

Best Answer

No, for the very simple reason that there is a maximum numerical value the PID can have. If a process has the highest PID, no child it forks can have a greater PID. The alternative to giving the child a lower PID would be to fail the fork() altogether, which wouldn't be very productive.

The PIDs are allocated in order, and after the highest one is used, the system wraps around to reusing the (free) lower ones, so you can get lower PIDs for a child in other cases too.

The default maximum PID on my system (/proc/sys/kernel/pid_max) is just 32768, so it's not hard to reach the condition where the wraparound happens.

$ echo $$
27468
$ bash -c 'echo $$'
1296
$ bash -c 'echo $$'
1297

If your system were to allocate PIDs randomly (like OpenBSD appears to do) instead of consecutively (like Linux), there would be two options. Either the random choice was made over the whole space of possible PIDs, in which case it would be obvious that a child's PID can be lower than the parent's. Or, the child's PID would be chosen by random from the values greater than the parent's PID, which would on average put it halfway between the parent's PID and the maximum. Processes forking recursively would then quickly reach the maximum and we'd be at the same point as mentioned above: a new fork would need to use a lower PID to succeed.