7

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.

12

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;
}
  • When PIDs run short (unlikely, of course), that random picker isn't going to perform so nicely. I'm surprised by the algorithm. – spender Sep 4 '18 at 15:15
  • OpenBSD sets very low process limits by default (256 per user) so unless you change that in login.conf or have a daemon class user run amok the process limit would be hit well before PIDs run short. – thrig Sep 4 '18 at 16:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.