首頁  >  文章  >  後端開發  >  php 判斷 linux 程式問題

php 判斷 linux 程式問題

WBOY
WBOY原創
2016-07-25 09:02:36817瀏覽

有时候在服务器上面写一些脚本的时候,经常要放到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<$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. //注:"www/pooy" 是程序里面包含的字符串!
  61. //现在php程序在linux运行是否通畅多了呢?
  62. //下载地址:http://www.pooy.net/php-linux-grep.html
复制代码


陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn