How to remove orphaned PID files

If you have multiple PID files for the same process ( e.g. 1_process_name.pid, 2_process_name.pid, ecc. ) you may have a situation like the one described above. So, how do you delete the PID files for the processes that are no longer running, without interfering with the running processes?


According to wikipedia.com a PID (proces identifier) is a number used by most operating system kernels — such as that of UNIX, macOS or Microsoft Windows — to uniquely identify an active process. This number may be used as a parameter in various function calls, allowing processes to be manipulated, such as adjusting the process’s priority or killing it altogether.

Some processes, for example, the moc music player and the MySQL daemon, write their PID to a documented file location, to allow other processes to look it up.

What to do in case, for some strange reason, that pid file never gets deleted when the process stops?

Well, 1st of all, you need to find out why that happens. However, this is not the reason I write this now.

In case the PID files are not deleted, although highly unlikely, it may happen that your hard drive will run out of space, so you need to find a way to remove those orphaned PID files.

A simple visual inspection of the directory containing the PID files ( e.g.  ls -ln /var/run/*.pid ) will show you all the PID files in /var/run/ directory.

If you have multiple PID files for the same process ( e.g. 1_process_name.pid, 2_process_name.pid, ecc. ) you may have a situation like the one described above.

So, how do you delete the PID files for the processes that are no longer running, without interfering with the running processes?

Check the below script:

 
#!/bin/bash

#Define the process name
process_name=example_process
processpid=$(ps axf | grep $process_name | grep -v grep | awk '{print $1}')  	        #get the running $process_name PID
dir=/var/run/*$process_name.pid                                     	   		#get all $process_name.pid files in /var/run/ directory
for f in $dir                                                           	   	#for each file in $dir
do
    pid=$(< "$f")                                                       	   	#assign to var $pid the value in the file
      if [ "$processpid" -eq "$pid" ]
            then 
                  echo "$process_name is running on PID $pid. Keeping $f intact."
            else 
                  echo "No process running on PID $pid. Deleting the $f file!"
                  rm -f $f                                               	   	#deleting the file corresponding to the value of $f
      fi
done