Sometimes when writing some scripts on the server, they often need to be put into crontab to run regularly. After a long time, there will be a problem, that is, the repeated running of the program consumes too many resources. How to deal with it? Puyu wrote two methods below. Original address: http://www.pooy.net/php-linux-grep.html
- //Pooy Blog
- // www.pooy.net
- // Welcome to communicate and discuss!
- //Sometimes when writing some scripts on the server, they often need to be put into crontab to run regularly. After a long time, there will be a problem, that is, the repeated operation of the program consumes too many resources. How to deal with it? Puyu wrote two methods below:
- //The first one: use regular matching in Linux
-
- function ifrun($clsname,$bf = 0)
- {
- //Detect below, if there is a process running , it will not run
- $str=shell_exec("/bin/ps ax > /home/root/".$clsname."_run.txt");
- $str=shell_exec("/bin/grep -c '" .$clsname.".php' /home/root/".$clsname."_run.txt");
-
- if($bf >0)
- {
- if($str >=$bf)
- {
- return 1;
- }
- else
- {
- return 0;
- }
- }
- else
- {
- if ($str>=2)
- {
- return 1;
- }
- else
- {
- return 0;
- }
- }
- }
-
- //Call:
-
- if (ifrun('pooy',5))
- {
- die("pooy is running");
- }
-
-
- //Remarks: pooy is the program pooy.php name!
-
- //The second method: write the process into the file, then use the file function to read and match the string
-
- system('ps -ef |grep wget > /root/pooy.txt');
- $arr=file('/root/pooy.txt');
- $total=count($arr);
- for($i=0;$i<$total;$i++){
- $count=array() ;
- if(stristr($arr[$i],'www/pooy') !== FALSE) {
- //echo '"earth" not found in string';
- $count[]='no';
- break;
- }
- }
- if(count($count) >= 1 )
- {
- echo "A same programs are running";
- exit();
- }else
- {
- echo "start________________________________________________";
- }
-
-
- //Note: "www/pooy" is the string contained in the program!
-
- //Is the PHP program running much more smoothly now on Linux?
-
- //Download address: http://www.pooy.net/php-linux-grep.html
Copy code
|