Process PID – What Determines the PID a Process Will Be Assigned

process

What determines what PID a process will be assigned?

It seems as if there is an upper bound for the integer value that's used for the ID; what is this limit and where is it defined?

Is there a range that is reserved for processes that are not created by the user?

Just to be clear, I'm asking this more out of curiosity than any practical reason.

Best Answer

What is the maximum value of the Process ID? covers the max; there are reserved processes (0 and 1 are notable) but not many, and there's a bit of code in the kernel that picks the next free integer (most unix) or instead a random pid (OpenBSD, or some flavors of Linux). OpenBSD calls this allocpid which can be found in kern/kern_fork.c

/* Find an unused pid */
pid_t
allocpid(void)
{
        static pid_t lastpid;
        pid_t pid;

        if (!randompid) {
                /* only used early on for system processes */
                pid = ++lastpid;
        } else {
                /* Find an unused pid satisfying lastpid < pid <= PID_MAX */
                do {
                        pid = arc4random_uniform(PID_MAX - lastpid) + 1 +
                            lastpid;
                } while (ispidtaken(pid));
        }

        return pid;
}