【问题标题】:execute linux commands from php scripts从 php 脚本执行 linux 命令
【发布时间】:2023-03-06 04:23:02
【问题描述】:

祝大家有美好的一天。

我需要向脚本发送请求,然后执行一些命令(基本上我需要在单击链接时启动 ffmpeg)。

我试过了:

exec("ffserver &");
exec("ffmpeg -i pipe.avi output.avi");
exec("mplayer -dumpstream someinput -dumpfile pipe.avi");

还有这个

shell_exec("ffserver &");
shell_exec("ffmpeg -i pipe.avi output.avi");
shell_exec("mplayer -dumpstream someinput -dumpfile pipe.avi");

在这两种情况下我都超时了。任何人都可以帮助我吗?谢谢。

【问题讨论】:

  • 注意:似乎在运行 shell 变体之后,无论我做什么都会超时:|所以... any1 还可以添加注释如何修复我的 php 解析器? (如果没有,我将重新安装 apache)

标签: php linux command-line command exec


【解决方案1】:

尝试在您的php.ini 文件中或通过设置函数set_time_limit 来增加PHP 脚本的执行时间

【讨论】:

    【解决方案2】:

    如果这只是超时错误,请尝试将 set_time_limit(xx);在您的代码之上。 其中 xx 对应等待的时间,以秒为单位。

    设置 0 表示没有时间限制,但如果您的脚本进入无限循环,或者它正在等待来自您的编码命令的反馈永远不会到达...

    【讨论】:

      【解决方案3】:

      您可以试试这个,它已由用户 bahri 在 bahri dot info 发布,作为对exec 的 PHP 手动条目的评论

      <?php
        function PsExecute($command, $timeout = 60, $sleep = 2) {
              // First, execute the process, get the process ID
      
              $pid = PsExec($command);
      
              if( $pid === false )
                  return false;
      
              $cur = 0;
              // Second, loop for $timeout seconds checking if process is running
              while( $cur < $timeout ) {
                  sleep($sleep);
                  $cur += $sleep;
                  // If process is no longer running, return true;
      
                 echo "\n ---- $cur ------ \n";
      
                  if( !PsExists($pid) )
                      return true; // Process must have exited, success!
              }
      
              // If process is still running after timeout, kill the process and return false
              PsKill($pid);
              return false;
          }
      
          function PsExec($commandJob) {
      
              $command = $commandJob.' > /dev/null 2>&1 & echo $!';
              exec($command ,$op);
              $pid = (int)$op[0];
      
              if($pid!="") return $pid;
      
              return false;
          }
      
          function PsExists($pid) {
      
              exec("ps ax | grep $pid 2>&1", $output);
      
              while( list(,$row) = each($output) ) {
      
                      $row_array = explode(" ", $row);
                      $check_pid = $row_array[0];
      
                      if($pid == $check_pid) {
                              return true;
                      }
      
              }
      
              return false;
          }
      
          function PsKill($pid) {
              exec("kill -9 $pid", $output);
          }
      ?>
      

      【讨论】:

      • 我会在几分钟内试一试...就在我修复 apache 之后:)。