php内置函数file_get_contents,在读取文件内容时如果磁盘繁忙或准备数据慢,file_get_contents会进入忙等待,期许数据会飞快的到来,而不会等哪怕1ms。
它也允许用来读取http内容,而且等待数据的行为和读取文件一样,而等待http返回和等待磁盘准备数据在时间上可不是一个量级的,所以当file_get_contents用来读取http内容时就进入了秒级的忙等待,从而导致cpu飙升。
不过貌似新版本的php修复了该问题,或与某些编译项有关。
问题再现:
strace -rv -p <PHP进程ID> -o strace.log
cat strace.log
----------------------------------------------
0.000019 select(8, [7], [7], [], {15, 0}) = 1 (out [7], left {15, 0}) <0.000006>
0.000029 poll([{fd=7, events=POLLIN|POLLPRI}], 1, 0) = 0 <0.000004>
0.000018 gettimeofday({1340090123, 417745}, NULL) = 0 <0.000004>
0.000017 gettimeofday({1340090123, 417763}, NULL) = 0 <0.000005>
0.000019 gettimeofday({1340090123, 417781}, NULL) = 0 <0.000005>
0.000019 select(8, [7], [7], [], {15, 0}) = 1 (out [7], left {15, 0}) <0.000010>
0.000034 poll([{fd=7, events=POLLIN|POLLPRI}], 1, 0) = 0 <0.000005>
0.000018 gettimeofday({1340090123, 417853}, NULL) = 0 <0.000005>
0.000018 gettimeofday({1340090123, 417871}, NULL) = 0 <0.000005>
0.000019 gettimeofday({1340090123, 417889}, NULL) = 0 <0.000005>
0.000019 select(8, [7], [7], [], {15, 0}) = 1 (out [7], left {15, 0}) <0.000006>
0.000028 poll([{fd=7, events=POLLIN|POLLPRI}], 1, 0) = 0 <0.000005>
0.000018 gettimeofday({1340090123, 417956}, NULL) = 0 <0.000007>
0.000020 gettimeofday({1340090123, 417974}, NULL) = 0 <0.000005>
0.000018 gettimeofday({1340090123, 417993}, NULL) = 0 <0.000004>
0.000032 select(8, [7], [7], [], {15, 0}) = 1 (out [7], left {15, 0}) <0.000006>
0.000036 poll([{fd=7, events=POLLIN|POLLPRI}], 1, 0) = 0 <0.000005>
0.000019 gettimeofday({1340090123, 418080}, NULL) = 0 <0.000005>
0.000018 gettimeofday({1340090123, 418097}, NULL) = 0 <0.000005>
0.000020 gettimeofday({1340090123, 418117}, NULL) = 0 <0.000005>
... ...
----------------------------------------------
php进入了持续数秒的非阻塞poll循环,直到数据返回,cpu使用率在此期间会飙升。
对于读取http内容,最好避免用file_get_contents,可以改用下面的自定义函数取代:
复制代码 代码示例:
<?php
/**
* url_get_contents函数
* edit: www.jb200.com
*/
function url_get_contents($strUrl, $boolUseCookie=false)
{
$ch = curl_init($strUrl);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPGET, true);
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch, CURLOPT_REFERER, $_SERVER['HTTP_REFERER']);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_MAXREDIRS, 3);
if ($boolUseCookie && is_array($_COOKIE) && count($_COOKIE) > 0) {
$cookie_str = '';
foreach($_COOKIE as $key => $value) {
$cookie_str .= "$key=$value; ";
}
curl_setopt($ch, CURLOPT_COOKIE, $cookie_str);
}
$response = curl_exec($ch);
if (curl_errno($ch) != 0) {
return false;
}
curl_close($ch);
return $response;
}