2

Everybody knows that PID number 1 is systemd (or something equivalent). And every process after that takes another PID, counting up.

However when there are 50 processes running (up to PID 50) and the process with PID 2 terminates and a new process starts, it won't be PID 2, but it will be PID 51. Why is that?

I noticed that e.g. with file descriptors, it's not like that, but rather, when I close file descriptor 4 and open a new file descriptor, it will have the number 4.

  • I'd imagine they do get recycled but you don't want to recycle pid's too quickly otherwise when you try to send a signal (or whatever else) to one pid you may hit something completely different than what you were intending. – Bratchley Apr 10 '16 at 16:14
  • 1
    File descriptors are a little bit different, the object responsible for creating them is also typically the only one who interacts with them. In which case you can be (or should be) certain what file you're interacting with because you're the one who needed to open it in the first place. – Bratchley Apr 10 '16 at 16:18
3

Most Unix variants allocate process IDs sequentially: 1, 2, 3, 4, ... When the largest possible PID value is reached, they start again at 1, skipping PIDs that already exist.

This is not an obligation. For example, OpenBSD assigns PIDs randomly, not sequentially; this is also an option on FreeBSD. The goal is improved security, though the benefits are dubious.

There is a (dubious) advantage to this behavior: it makes it rare for a process ID to be reused immediately after the process dies. There are many programs out there that monitor processes and assume that after a process dies, the PID will not be in use — which breaks if the PID is used by a new process. Those programs do have an excuse: there are no good APIs to monitor a process except from its parent. But such programs are widespread enough that OpenBSD avoids reusing a PID for a little while (a few minutes, if I remember correctly) after a process dies.

The main reason for this behavior is that it's how it was done on traditional Unix systems, and there's no strong reason to change. For file descriptors, Unix historically used the first free fd number, and that behavior has been made an official standard so all Unix/POSIX systems have to do it this way.

  • For the OpenBSD part, does it just report PID exhaustion until a PID's waiting period is over with? – Bratchley Apr 11 '16 at 15:09

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.