2024-07-28 05:00:06

PHP执行后台进程

我需要在用户操作时执行目录复制,但目录相当大,因此我希望能够在用户不知道完成复制所需时间的情况下执行这样的操作。

任何建议都将不胜感激。


当前回答

我知道这是一个有100年历史的帖子,但不管怎样,我觉得它可能对某人有用。你可以在页面的某个地方放一个不可见的图像,指向需要在后台运行的url,就像这样:

<img src="run-in-background.php" border="0" alt="" width="1" height="1" />

其他回答

用任何方便的语言(php/bash/perl/etc)将进程作为服务器端脚本编写,然后从php脚本中的进程控制函数调用它。

该函数可能会检测是否使用标准io作为输出流,如果是,则设置返回值,如果不是,则结束

proc_close( proc_open( "./command --foo=1 &", array(), $foo ) );

我在命令行中使用“sleep 25s”作为命令快速测试了这个功能,效果非常好。

(答案在这里)

使用此函数在后台运行程序。它是跨平台的,完全可定制的。

<?php
function startBackgroundProcess(
    $command,
    $stdin = null,
    $redirectStdout = null,
    $redirectStderr = null,
    $cwd = null,
    $env = null,
    $other_options = null
) {
    $descriptorspec = array(
        1 => is_string($redirectStdout) ? array('file', $redirectStdout, 'w') : array('pipe', 'w'),
        2 => is_string($redirectStderr) ? array('file', $redirectStderr, 'w') : array('pipe', 'w'),
    );
    if (is_string($stdin)) {
        $descriptorspec[0] = array('pipe', 'r');
    }
    $proc = proc_open($command, $descriptorspec, $pipes, $cwd, $env, $other_options);
    if (!is_resource($proc)) {
        throw new \Exception("Failed to start background process by command: $command");
    }
    if (is_string($stdin)) {
        fwrite($pipes[0], $stdin);
        fclose($pipes[0]);
    }
    if (!is_string($redirectStdout)) {
        fclose($pipes[1]);
    }
    if (!is_string($redirectStderr)) {
        fclose($pipes[2]);
    }
    return $proc;
}

注意,在命令启动后,默认情况下,该函数关闭正在运行进程的stdin和stdout。你可以通过$redirectStdout和$redirectStderr参数将进程输出重定向到某个文件中。

windows用户注意: 不能以以下方式将stdout/stderr重定向为null:

startBackgroundProcess('ping yandex.com', null, 'nul', 'nul');

然而,你可以这样做:

startBackgroundProcess('ping yandex.com >nul 2>&1');

*nix用户注意事项:

1)如果你想得到实际的PID,使用exec shell命令:

$proc = startBackgroundProcess('exec ping yandex.com -c 15', null, '/dev/null', '/dev/null');
print_r(proc_get_status($proc));

2)使用$stdin参数,如果你想传递一些数据到你的程序的输入:

startBackgroundProcess('cat > input.txt', "Hello world!\n");

一个适用于Windows和Linux的解决方案。在我的github页面上找到更多信息。

function run_process($cmd,$outputFile = '/dev/null', $append = false){
                    $pid=0;
                if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {//'This is a server using Windows!';
                        $cmd = 'wmic process call create "'.$cmd.'" | find "ProcessId"';
                        $handle = popen("start /B ". $cmd, "r");
                        $read = fread($handle, 200); //Read the output 
                        $pid=substr($read,strpos($read,'=')+1);
                        $pid=substr($pid,0,strpos($pid,';') );
                        $pid = (int)$pid;
                        pclose($handle); //Close
                }else{
                    $pid = (int)shell_exec(sprintf('%s %s %s 2>&1 & echo $!', $cmd, ($append) ? '>>' : '>', $outputFile));
                }
                    return $pid;
            }
            function is_process_running($pid){
                if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {//'This is a server using Windows!';
                        //tasklist /FI "PID eq 6480"
                    $result = shell_exec('tasklist /FI "PID eq '.$pid.'"' );
                    if (count(preg_split("/\n/", $result)) > 0 && !preg_match('/No tasks/', $result)) {
                        return true;
                    }
                }else{
                    $result = shell_exec(sprintf('ps %d 2>&1', $pid));
                    if (count(preg_split("/\n/", $result)) > 2 && !preg_match('/ERROR: Process ID out of range/', $result)) {
                        return true;
                    }
                }
                return false;
            }
            function stop_process($pid){
                    if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {//'This is a server using Windows!';
                            $result = shell_exec('taskkill /PID '.$pid );
                        if (count(preg_split("/\n/", $result)) > 0 && !preg_match('/No tasks/', $result)) {
                            return true;
                        }
                    }else{
                            $result = shell_exec(sprintf('kill %d 2>&1', $pid));
                        if (!preg_match('/No such process/', $result)) {
                            return true;
                        }
                    }
            }

PHP脚本不同于其他桌面应用程序开发语言。在桌面应用程序语言中,我们可以设置守护线程来运行后台进程,但在PHP中,当用户请求一个页面时,进程就会发生。但是,可以使用php脚本运行的服务器的cron作业功能来设置后台作业。

假设这是在Linux机器上运行的,我总是这样处理它:

exec(sprintf("%s > %s 2>&1 & echo $! >> %s", $cmd, $outputfile, $pidfile));

这将启动命令$cmd,将命令输出重定向到$outputfile,并将进程id写入$pidfile。

这使您可以轻松地监视进程正在做什么以及它是否仍在运行。

function isRunning($pid){
    try{
        $result = shell_exec(sprintf("ps %d", $pid));
        if( count(preg_split("/\n/", $result)) > 2){
            return true;
        }
    }catch(Exception $e){}

    return false;
}