Wednesday, March 5, 2008

number of processes running..

We can replace xyz.lock functionality by counting the number of processes running.
As many of us use some xyz.lock file just to ensure that same process should not run more than one time simultaneously.

I faced a little problem with this concept (lock file) :

Problems (lock file):
1. In case a script dies without deleting the lock file, when second time scripts executes, It checks for the lock file and exits without doing anything assuming that one thread is already running, which is not true.
2. We have to manually delete the file (which can be done only If we locate the problem that script died)

Solution (check process):
1. Instead of using lock file concept, we should use checkProcess (sample code provided). Yes, you can change the code according to your requirement, after all it is open source), which will check If process is running or not, and will work accordingly.
A better practice with this is that, we also ensure to get alert to find the problem too (as we do in the lock file concept too (assuming)).

Benefit :
1. If some script is running in cron very frequently (even if daily), the very next attempt will not fail if the previous attempt fails, and it will help in automating the system more efficiently.

/**
* Function : checkProcess
* Input : name of the process like garbageCollector
* Output : count of the processes running. In case of garbageCollector, it will be always in (0,1) ideally.
* Author : Vishnu Kumar Agarwal
* Description : returns count of the processes currently running
*/
function checkProcess($processName)
{
return $processCount = shell_exec("ps ax | grep $processName | grep -v grep | wc -l");
}

echo "Count",checkProcess("garbageCollector");

No comments: