19

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
  • 67,283
  • 35
  • 116
  • 255
Athiri
  • 659
  • 1
  • 10
  • 18

2 Answers2

24

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.

0

Yes, can be reused. Just to add to Stéphane Chazelas answer:

In case you need this for scripting, for example you want to kill $PID where $PID is a single child process and you are not sure if you are killing the right process, then at least in bash you can check if the process with some $PID is a child of current shell like this:

if grep -qFx $PID <(jobs -rp); then
   kill $PID
fi

Here jobs -rp prints children PIDs and grep -qFx $PID returns 0 when $PID is matched.

This approach helps when you need to distinguish a single child from other system processes. But if you want to distinguish between the multiple children of the current shell, you probably need to notify the current shell on each child exit. For example:

{
    trap "echo $BASHPID >> exited" EXIT
    # some long action
} &

Here, when the child process exits, it writes its PID to the file exited. The main process can then check if the process with specific PID is already exited before killing it.

Note. The SIGCHLD signal is sent to the current shell each time child exits. This can be used to optimize the process (eg. trap "something..." SIGCHLD)

Alek
  • 155