Home  >  Article  >  Backend Development  >  PHP determines linux program problems

PHP determines linux program problems

WBOY
WBOYOriginal
2016-07-25 09:02:36817browse

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

  1. //Pooy Blog
  2. // www.pooy.net
  3. // Welcome to communicate and discuss!
  4. //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:
  5. //The first one: use regular matching in Linux
  6. function ifrun($clsname,$bf = 0)
  7. {
  8. //Detect below, if there is a process running , it will not run
  9. $str=shell_exec("/bin/ps ax > /home/root/".$clsname."_run.txt");
  10. $str=shell_exec("/bin/grep -c '" .$clsname.".php' /home/root/".$clsname."_run.txt");
  11. if($bf >0)
  12. {
  13. if($str >=$bf)
  14. {
  15. return 1;
  16. }
  17. else
  18. {
  19. return 0;
  20. }
  21. }
  22. else
  23. {
  24. if ($str>=2)
  25. {
  26. return 1;
  27. }
  28. else
  29. {
  30. return 0;
  31. }
  32. }
  33. }
  34. //Call:
  35. if (ifrun('pooy',5))
  36. {
  37. die("pooy is running");
  38. }
  39. //Remarks: pooy is the program pooy.php name!
  40. //The second method: write the process into the file, then use the file function to read and match the string
  41. system('ps -ef |grep wget > /root/pooy.txt');
  42. $arr=file('/root/pooy.txt');
  43. $total=count($arr);
  44. for($i=0;$i<$total;$i++){
  45. $count=array() ;
  46. if(stristr($arr[$i],'www/pooy') !== FALSE) {
  47. //echo '"earth" not found in string';
  48. $count[]='no';
  49. break;
  50. }
  51. }
  52. if(count($count) >= 1 )
  53. {
  54. echo "A same programs are running";
  55. exit();
  56. }else
  57. {
  58. echo "start________________________________________________";
  59. }
  60. //Note: "www/pooy" is the string contained in the program!
  61. //Is the PHP program running much more smoothly now on Linux?
  62. //Download address: http://www.pooy.net/php-linux-grep.html
Copy code


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn