Search code examples
linuxpid

How come pid files are used when pids can clash with an unrelated process?


It seems that a common way of running only one copy of a process is to write a pid to a file and then on start check whether a process with that pid exists. I imagine OS is trying not to reuse a pid quickly after a process has crashed, but since the number of pids is limited, sooner or later there is going to be another unrelated process using that pid. And the original one won't start. How can this situation be avoided?


Solution

  • Typically you would also check for the process name. For example the following will return 1 if there is a process called fork-server running on PID 10616:

    ps -xp 10616 | grep fork-server | wc -l
    

    It is of course still possible to have a collision, but the likelihood should be much less.