8

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.

chb
  • 634

1 Answers1

13

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;
}
thrig
  • 34,938
  • 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 04 '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 04 '18 at 16:04
  • It surprises me the logic of the two code paths. Only the random path calls ispidtaken(). In the other case, if the system reaches the maximum pid value, rollover to 0... does allocpid() return it as usable? mmh – Massimo Sep 25 '19 at 04:40