In our application, we start some background processes. The pid of these processes is saved to a file.
pids values are re-used when the maximum is reached or when the system is rebooted.
How can I reliably check that the process with pid X is still the same process for which X was stored.
I've read https://serverfault.com/questions/366474/whats-a-proper-way-of-checking-if-a-pid-is-running and https://stackoverflow.com/questions/3043978/how-to-check-if-a-process-id-pid-exists but these solutions never check if the process that has pid X is the still same process as the one for which the pid was stored.
I need this info to reliably
- check the process is still running
- kill the process without risking to kill a different process that now has pid X
related https://serverfault.com/questions/279178/what-is-the-range-of-a-pid-on-linux-and-solaris
I will post my current solution. I'd like to know if it's a sensible approach and if there are better ways to do this.
kill -0 $pid
; e. g.if kill -0 "$pid"; then printf "PID %d exists and is running.\n" "$pid"
.