用于检查Linux进程的PHP脚本是否处于活动状态

时间:2015-08-13 18:32:45

标签: php linux

我刚创建了一个脚本来检查进程是否处于活动状态,下面是我的PHP脚本。进程在Linux服务器中是活动的是16269,但它显示“进程已死”。有没有办法检查进程名称?

<?php

  $pid = $_POST["pid"] ;

  function checkPid($pid)
    {
     // create our system command
     $cmd = "ps $pid";

     // run the system command and assign output to a variable ($output)
     exec($cmd, $output, $result);

     // check the number of lines that were returned
     if(count($output) >= 2){

          // the process is still alive
          echo '<h1> Process is running </h1>';
          echo '<img src="/proview/green.gif" width="16" height="16" alt="Process is Alive" />';
          return true;
     }

     // the process is dead
     echo '<h1> Process is dead </h1>';
     echo '<img src="/proview/red.gif" width="16" height="16" alt="Process is dead"/>';
     return false;

}

if(isset($_POST['submit']))
{
   checkPid($pid);
} 
?>
<body>
<p>


<form method="post" action="index.php">
    <input type="text" name="pid">
    <input type="submit" value="Check Processe by ID" name="submit">  
</form>

</body>

这是网址:http://fanciedmedia.in/proview/index.php

1 个答案:

答案 0 :(得分:0)

尝试以下方法:

<?php

function checkPid($pid)
{

      // returns something like:
      // 8987 pts/0    00:00:00 bash
      $result =  exec("ps -A|grep {$pid}");

      if(preg_match("/{$pid}/",$result))
      {
         echo "PID {$pid} is running.";
         return true;
      }
      else
      {
         echo "PID {$pid} is NOT running.";
         return false;
      }

}

if( isset($_POST['submit']) && isset($_POST["pid"]) )
{
   checkPid( $_POST["pid"] );
} 
?>
<body>
<p>


<form method="post" action="index.php">
    <input type="text" name="pid">
    <input type="submit" value="Check Processe by ID" name="submit">  
</form>

</body>

我的工作正常。祝你好运!