#!/bin/bash

# clean /dev/shm
find /dev/shm -name "shmpipe*" -and -not -exec fuser -s {} ';' -and -exec rm {} ';'

#collect all semaphore ID
for SEMID in `ipcs -s|egrep -v -e "Semaphore|key"|sed '/^$/d'|awk '{print $2}'|sort -u`
	do
		#GETPID of semaphore
		PID=`ipcs -s -i $SEMID|tail -2|head -1|awk '{print $NF}'`
		#GET PROCESS ID
		#Ignore process ID 0 which is main process & test PID greater than 0
		if [ $PID -gt 0 ]; then

			#Test of PID exists in process list, if exits then don't do anything.
			if ps -p $PID > /dev/null; then
				#running process are
				echo "+++ Semaphore of running process found: SEMID: $SEMID, PID: $PID" &> /dev/null
			else
				# dead process are, kill corresponding semaphore of related PID is not existing.
				echo "--- Semaphore of dead process found: SEMID: $SEMID, PID: $PID" &> /dev/null

				#cleaning semaphore of dead process :
				ipcrm -s $SEMID
			fi
		fi
 	done
