Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

It seems many programmers are happy with saving a PID to a file, and then later read and use the PID as if it was guaranteed to be the same process. It seems the general idea is that the odds are good enough to ignore. How can I simply demonstrate this problem? Ideally in such a way that existing shell scripts can be adapted to demonstrate this with the minimum of trial and error.

share|improve this question
To end up killing the wrong process you need 1) a process that uses a PID file to die without removing the PID file, 2) the process not be restarted by systemd/init/launchd/whatever, which would put a new PID in the PID file, 3) 100,000 PIDs have been assigned so that PIDs start being reused, 4) a kill() system call directed at the PID of that old process while a new process is using the PID. If the user running the process isn't root, the odds of killing the wrong process decrease even further. There's no way to orchestrate these conditions easily on a live system. –  Kyle Jones Apr 24 '13 at 1:05
@KyleJones On Ubuntu 12.04 at least /proc/sys/kernel/pid_max contains 32768, so 100,000 is an overestimation. And I don't see how point 4 is relevant - I've seen daemons which will kill the value in the PID file when stopping or restarting them. –  l0b0 Apr 24 '13 at 6:55

1 Answer 1

Using exec is a pretty good demonstration of PID reuse:


cat > foo << 'EOF'
echo "Inside foo."
sleep 5
exec ./bar

cat > bar << 'EOF'

echo "Inside bar."
sleep 5

chmod a+x foo bar

./foo &

while sleep 3; do
    [[ -f "/proc/$!/cmdline" ]] || break
    printf 'pid %d == %s\n' "$!" "$(tr '\0' ' ' < "/proc/$!/cmdline")"

rm foo bar

Running this script yields something like the following:

$ ./script
Inside foo.
pid 4953 == /bin/bash ./script
Inside bar.
pid 4953 == /bin/bash /tmp/tmp.AvDLtMWYPy/bar
pid 4953 == /bin/bash /tmp/tmp.AvDLtMWYPy/bar

You can exec arbitrary programs, so there is no guarantee (at all) that the process at that PID is the same, or even similar.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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