2013-08-02 52 views
0

我试图在某些单元测试开始时启动PHP的内置web服务器。目标是让相同的脚本启动Web服务器,然后连接到它来验证我们的卷曲包装库的行为是否适当。通过exec()启动PHP网络服务器时,curl()拒绝连接()

脚本:

<?php 
    echo "Starting server...\n"; 
    exec("php -S localhost:8000 -t /path/to/files > /dev/null & echo $!", $output); 


    $ch = curl_init("http://localhost/"); 
    curl_setopt($ch, CURLOPT_PORT, 8000); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
    curl_exec($ch); 

    if(curl_errno($ch)) 
    { 
      echo 'Curl error: ' . curl_error($ch); 
    } 

    // Close handle 
    curl_close($ch); 

    echo "PID: ".$output[0]."\n"; 
    exec('kill '.$output[0]); 
?> 

当我运行上面的脚本,我得到这个错误:

Curl error: Failed connect to localhost:8000; Connection refused 

注:

  • 的Web服务器不启动,如果删除kill在脚本的结尾我可以看到在进程列表中运行的webserver
  • 如果我开始了PHP的命令行上的Web服务器我的PHP脚本可以连接到它
  • 如果我从启动PHP的Web服务器的另一个 PHP脚本上面的脚本可以连接到它
  • curl命令行可以连接到PHP的网络服务器开始

我只能猜测,当一个进程尝试连接到它的进程启动PHP的Web服务器时,有东西被阻止或发生?

PHP 5.4.15

CentOS版本5.6(最终)

回答

2

我认为你赶! 您可以使用“&”

然后尝试连接开始在后台Web服务器,但在那一刻,你的Web服务器没有完全启动,所以它不听!

<?php 
    echo "Starting server...\n"; 
    exec("php -S localhost:8000 -t /path/to/files > /dev/null & echo $!", $output); 


// sleep 1-5 seconds 
sleep (5); 

$ch = curl_init("http://localhost/"); 
curl_setopt($ch, CURLOPT_PORT, 8000); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
curl_exec($ch); 

if(curl_errno($ch)) 
{ 
     echo 'Curl error: ' . curl_error($ch); 
} 

// Close handle 
curl_close($ch); 

echo "PID: ".$output[0]."\n"; 
exec('kill '.$output[0]); 
+0

哇,简直不敢相信它是那么简单!谢谢! –

+0

该死的异步! :D:D:D –