2024-07-28 05:00:06

PHP执行后台进程

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

任何建议都将不胜感激。


当前回答

您是否可以安排派生一个单独的进程,然后在后台运行您的副本?我已经有一段时间没有使用PHP了,但是函数pcntl-fork看起来很有前途。

其他回答

感谢这个答案:Symfony process Component是运行后台进程的一个完美工具,它基于proc_*函数,但是使用起来更容易。有关更多信息,请参阅其文档。

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

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

老问题的新答案。使用这个库,下面的代码将生成一个异步/并行PHPThread来执行后台工作。

必须有pcntl, posix和套接字扩展名 在CLI模式下设计/测试。

EZ代码示例:

 function threadproc($thread, $param) {
 
    echo "\tI'm a PHPThread.  In this example, I was given only one parameter: \"". print_r($param, true) ."\" to work with, but I can accept as many as you'd like!\n";
 
    for ($i = 0; $i < 10; $i++) {
        usleep(1000000);
        echo "\tPHPThread working, very busy...\n";
    }
 
    return "I'm a return value!";
}
 

$thread_id = phpthread_create($thread, array(), "threadproc", null, array("123456"));
 
echo "I'm the main thread doing very important work!\n";
 
for ($n = 0; $n < 5; $n++) {
    usleep(1000000);
    echo "Main thread...working!\n";
}
 
echo "\nMain thread done working.  Waiting on our PHPThread...\n";
 
phpthread_join($thread_id, $retval);
 
echo "\n\nOur PHPThread returned: " . print_r($retval, true) . "!\n";

假设这是在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;
}

如果你只需要在后台做一些事情,而不需要PHP页面等待它完成,你可以使用另一个(后台)PHP脚本,用wget命令“调用”。当然,与系统上的任何其他PHP脚本一样,这个后台PHP脚本将以特权执行。

下面是一个在Windows上使用gnuwin32包中的wget的例子。

后台代码(文件test-proc-bg.php)为例…

sleep(5);   // some delay
file_put_contents('test.txt', date('Y-m-d/H:i:s.u')); // writes time in a file

前台脚本,调用…

$proc_command = "wget.exe http://localhost/test-proc-bg.php -q -O - -b";
$proc = popen($proc_command, "r");
pclose($proc);

你必须使用popen/pclose才能正常工作。

wget选项:

-q    keeps wget quiet.
-O -  outputs to stdout.
-b    works on background