php - 从 php 脚本执行 linux 命令

标签 php linux command-line command exec

大家好。

我需要向脚本发送请求然后执行一些命令(基本上我需要在单击链接时启动 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");

在这两种情况下我都超时了。任何人都可以帮我解决这个问题吗?谢谢。

最佳答案

您可以试试这个,它已由用户 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);
    }
?>

关于php - 从 php 脚本执行 linux 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5470021/

相关文章:

java - 如何使用同一个实例多次调用 JAR 文件?

linux - 如何简洁地执行 Linux 嵌套命令行?

用于选择查询的 PHP While 循环

linux - apt-get 没有安装任何 linux 服务器

linux - 需要oneliner在unix中第二行第N次出现定界符后插入字符

php - 通过命令行运行 php

php array_merge_recursive 保留数字键

javascript - 将信息从 PHP 传递到 JQUERY 的方法?

生成安全 URL 的 PHP 代码?

php - 岩石上的恶魔