在Windows机器上运行长时间后台进程的PHP

4

我有一个使用Curl在PHP中编写的脚本,逐个访问长列表中的URL并将响应写入文件。我希望从浏览器上传列表,并在后台完成其余处理(无需等待响应)。我已经尝试了以下解决方案 -

    $command = "C:\wamp\bin\php\php5.5.12\php.exe ../background_process/subscribe_bg.php ".$file_temp_path;
    shell_exec(sprintf('%s > /dev/null 2>/dev/null &', $command));

这将成功运行脚本,但会让浏览器等待。(在Linux机器上可能会在后台运行。)
    $command = "C:\wamp\bin\php\php5.5.12\php.exe ../background_process/subscribe_bg.php ".$file_temp_path;

    execInBackground($command);

    function execInBackground($cmd) { 
        if (substr(php_uname(), 0, 7) == "Windows"){ 
            pclose(popen("start /B ". $cmd, "r"));  
        } 
        else { 
            exec($cmd . " > /dev/null &");   
        } 
    }

我发现了一个适用于Windows机器的解决方案,但对我不起作用。脚本根本没有执行。

请建议在Windows机器上使用PHP在后台运行长时间进程(不是非常长,大约30-40分钟)的最佳实践。


谢谢,sainiankit。这行代码:pclose(popen("start /B ". $cmd, "r")); 对我有效。我在Windows 7上运行PHP 5.3。 - kdanylo
脚本根本没有执行。实际上,它会执行,但是一旦父进程(即http请求)结束,它就会停止。后台作业实现(或者在紧急情况下使用forking)太广泛了,无法在Stackoverflow上进行描述 - 但这就是你所要求的。 - AD7six
2个回答

2
这在Windows机器上运行得很完美,脚本的所有输出都写入到$response_file_path中 -
$command = $PHP_DIR." ../background_process/subscribe_bg.php -p=".$file_path_arg." >../sublogs/responses/".$file_response_path." 2>../sublogs/error_logs/err.txt";

execInBackground($command)

function execInBackground($cmd) {
    if (substr(php_uname(), 0, 7) == "Windows"){
        pclose(popen("start /B ". $cmd, "r"));
        return 1;
    }
    else {
        return 0;
        //Or the code for linux machine.
    }
}

确切地说,我的意思是你之前的命令没有将输出重定向到文件中,所以它之前无法正常工作。谢谢。 - kdanylo
哦,没错!确实是这样,这让浏览器等待进程完成。 - sainiankit

0

我认为你应该将后台进程的输出重定向到另一个文件中。由于你没有进行重定向,PHP 正在等待它完成。请在你的命令中添加“>”重定向符号:

$command = "C:\wamp\bin\php\php5.5.12\php.exe ../background_process/subscribe_bg.php ".$file_temp_path . " > out.log ";

祝你好运! Danylo


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接