16

In a Linux operating system, is there any chance that a PID can be reused?

For example, A PID is named 2252. This PID is dead and erased from kernel process table. Is there any chance that the process table can re-use a same PID for a new process, or it will not be used in any of the upcoming processes?

Jeff Schaller
  • 66,199
  • 35
  • 114
  • 250
Athiri
  • 559
  • 1
  • 7
  • 18

1 Answers1

18

Of course. Otherwise a system could only run 32768 processes (or whatever the maximum pid number is on the system) per boot.

As long as a process is dead and has been waited for (by its parent, or the sub child reaper or init if the parent is dead), its pid can be reused.

You see scripts doing things like:

cmd1 & pid1=$!
something else
cmd2 & pid2=$!
more things
kill "$pid1" "$pid2"

Those are approximations as the shell (most shells) language doesn't give you any better API to handle child processes.

There's no guarantee that $pid1 and/or $pid2 will still refer to the processes that were started earlier if those processes may have died. $pid1 and $pid2 could also be the same (if cmd1 has died by the time cmd2 is started). So kill could kill the wrong processes.

In practice, it's rarely a problem especially on systems where pids are assigned in sequence as it takes quite some time for pid numbers to wrap. But it can become so when the pid table gets full (like when it's filled with zombie processes) and some attackers can get advantage of that.

Stéphane Chazelas
  • 522,931
  • 91
  • 1,010
  • 1,501