Rumah  >  Artikel  >  pembangunan bahagian belakang  >  PHP如何判断程序运行状态

PHP如何判断程序运行状态

WBOY
WBOYasal
2016-07-25 09:13:111606semak imbas

在linux系统中,运行一些脚本时,经常要放到crontab里面定时运行。 时间长了就有一个问题,那就是程序重复运行消耗太多的资源,怎么处理呢?

写了两种方法: 第一种:用linux中正则匹配

  1. function ifrun($clsname,$bf = 0)

  2. {
  3. //下面进行检测,如有一个进程正在运行,则不运行
  4. $str=shell_exec("/bin/ps ax > /home/root/".$clsname."_run.txt");
  5. $str=shell_exec("/bin/grep -c '".$clsname.".php' /home/root/".$clsname."_run.txt");
  6. if($bf >0)

  7. {
  8. if($str >=$bf)
  9. {
  10. return 1;
  11. }
  12. else
  13. {
  14. return 0;
  15. }
  16. }
  17. else
  18. {
  19. if ($str>=2)
  20. {
  21. return 1;
  22. }
  23. else
  24. {
  25. return 0;
  26. }
  27. }
  28. }
复制代码

调用: if (ifrun('pooy',5)) { die("pooy is running"); } 备注:pooy是程序pooy.php的名称!

第二种:把进程写到文件里面,然后用file函数去读取然后去匹配字符串

  1. system('ps -ef |grep wget > /root/pooy.txt');

  2. $arr=file('/root/pooy.txt');
  3. $total=count($arr);
  4. for($i=0;$i $count=array();
  5. if(stristr($arr[$i],'www/pooy') !== FALSE) {
  6. //echo '"earth" not found in string';
  7. $count[]='no';
  8. break;
  9. }
  10. }
  11. if(count($count) >= 1 )

  12. {
  13. echo "A same programs are running";
  14. exit();
  15. }else
  16. {
  17. echo "start__________________________________________________";
  18. }
复制代码

注:”www/pooy” 是程序里面包含的字符串!

现在php程序在linux运行就会通畅多了。

小编总结: 在linux系统中调试一些简单的php程序时,特别时需要定时执行的php程序时,crontab是个不错的选择,它类似于windows下的计划任务,不过比win下的方便,建议大家多多尝试。



Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn