<?php
echo"Programstartsat".date('h:i:s').".\n";
$timeout=10;
$result=array();
$sockets=array();
$convenient_read_block=8192;
$delay=15;
$id=0;
while($delay>0){
$s=stream_socket_client("phaseit.net:80",$errno,
$errstr,$timeout,
STREAM_CLIENT_ASYNC_CONNECT|STREAM_CLIENT_CONNECT);
if($s){
$sockets[$id++]=$s;
$http_message="GET/demonstration/delay?delay=".
$delay."HTTP/1.0\r\nHost:phaseit.net\r\n\r\n";
fwrite($s,$http_message);
}else{
echo"Stream".$id."failedtoopencorrectly.";
}
$delay-=3;
}
while(count($sockets)){
$read=$sockets;
stream_select($read,$w=null,$e=null,$timeout);
if(count($read)){
foreach($read as $r){
$id=array_search($r,$sockets);
$data=fread($r,$convenient_read_block);
if(strlen($data)==0){
echo"Stream ".$id." closes at ".date('h:i:s').".\n";
fclose($r);
unset($sockets[$id]);
}else{
$result[$id].=$data;
}
}
}else{
echo"Time-out!\n";
break;
}
}
<?php
echo "Program starts at ". date('h:i:s') . ".\n";
$timeout=10;
$streams=array();
$handles=array();
$delay=3;
for ($id=0; $id <= 1; $id++) {
$error_log="/tmp/error" . $id . ".txt";
$descriptorspec=array(
0 => array("pipe", "r"),
1 => array("pipe", "w"),
2 => array("file", $error_log, "w")
);
$cmd='sleep ' . $delay . '; echo "Finished with delay of ' .
$delay . '".';
$handles[$id]=proc_open($cmd, $descriptorspec, $pipes);
$streams[$id]=$pipes[1];
$all_pipes[$id]=$pipes;
$delay -= 2;
}
while (count($streams)) {
$read=$streams;
stream_select($read, $w=null, $e=null, $timeout);
foreach ($read as $r) {
$id=array_search($r, $streams);
echo stream_get_contents($all_pipes[$id][1]);
if (feof($r)) {
fclose($all_pipes[$id][0]);
fclose($all_pipes[$id][1]);
$return_value=proc_close($handles[$id]);
unset($streams[$id]);
}
}
}
这里的关键在于 PHP 启动了两个独立子进程,取回待完成的第一个进程的输出,然后取回第二个进程的输出,即使后者启动得较早。如果主机是多处理器计算机,并且操作系统已正确配置,则操作系统本身负责将各个子程序分配给不同的处理器。这是在多处理器主机中良好应用 PHP 的一种方法。