Heim  >  Artikel  >  Backend-Entwicklung  >  php 判断 linux 程序问题

php 判断 linux 程序问题

WBOY
WBOYOriginal
2016-07-25 09:02:36815Durchsuche

有时候在服务器上面写一些脚本的时候,经常要放到crontab里面定时运行。时间长了就有一个问题,那就是程序重复运行消耗太多的资源,怎么处理呢?下面璞玉写了两种方法.
原文地址:http://www.pooy.net/php-linux-grep.html

  1. //璞玉(pooy)博客
  2. // www.pooy.net
  3. // 欢迎交流,讨论!
  4. //有时候在服务器上面写一些脚本的时候,经常要放到crontab里面定时运行。时间长了就有一个问题,那就是程序重复运//行消耗太多的资源,怎么处理呢?下面璞玉写了两种方法:
  5. //第一种:用linux里面的正则匹配
  6. function ifrun($clsname,$bf = 0)
  7. {
  8. //下面进行检测,如有一个进程正在运行,则不运行
  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. //调用:
  35. if (ifrun('pooy',5))
  36. {
  37. die("pooy is running");
  38. }
  39. //备注:pooy是程序pooy.php的名称!
  40. //第二种:把进程写到文件里面,然后用file函数去读取然后去匹配字符串
  41. system('ps -ef |grep wget > /root/pooy.txt');
  42. $arr=file('/root/pooy.txt');
  43. $total=count($arr);
  44. for($i=0;$i $count=array();
  45. if(stristr($arr[$i],'www/pooy') !== FALSE) {
  46. //echo '"earth" not found in string';
  47. $count[]='no';
  48. break;
  49. }
  50. }
  51. if(count($count) >= 1 )
  52. {
  53. echo "A same programs are running";
  54. exit();
  55. }else
  56. {
  57. echo "start__________________________________________________";
  58. }
  59. //注:"www/pooy" 是程序里面包含的字符串!
  60. //现在php程序在linux运行是否通畅多了呢?
  61. //下载地址:http://www.pooy.net/php-linux-grep.html
复制代码


Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn