Pid file and process check

Hello,
I am running ubuntu14.04
What I am trying to do is restart a process with a shell when pid is dead.
I restored pid nr in a file and check with ps aux | grep -v grep | grep $(cat *.pid)| awk '{ print $2 }'
While surfing on google, I have found an answer saying that restoring pid in a file for this purpose is not a good way.

Do you believe that bold part of the quote is correct?
How come a new process can have a pid nr of an old dead process?

Thanks in advance
Boris

I don't know of any OS that randomly picks the next PID to use when creating a new process. But, it is theoretically possible to do it that way.

Most of the systems I have worked on have a maximum PID value that is a configuration parameter. They start out assigning PIDs from 1 and increment the PID they want to assign by one every time a new process is created (e.g., by fork ()), but before assigning that value, they check to see if that PID is currently in use. If it is in use, the OS tries again with the next possible PID until it finds one that is not in use. Using this method, you won't run into problems with PID recycling unless there are so many processes running on your system that you don't have many possible PIDs available that aren't in use.

Furthermore, if you have a ps utility that conforms to POSIX requirements, you can ask ps to just print the fields you want to see and not have to worry about some unexpected value in a field you aren't interested in containing what looks like a PID. (Look at your man page for the ps -o format option.)

3 Likes

/var/run/ is supposed to be writable and volatile: to be cleaned during system boot, or an in-memory file system (e.g. tmpfs).
The daemon process should create the pidfile, and remove it when it is killed, in an exit handler that captures all kill signals. (Please do not kill -9 the daemon process!)
Further, an init script can check for an existing pidfile, if yes then check for validity and refuse to start a second daemon process. If the daemon-process runs as non-root, the init script creates a subdirectory and chowns it to the daemon user.

AIX generates random and big (7 or 8 digits) pids.

2 Likes