您可以使用proc_open打开dig命令的管道,stream_select它并等待5秒,然后读取并关闭proc.
或多或少这样:
function getip()
{
$ip = null;
$descriptorspec = array(
0 => array("pipe", "r"), // stdin is a pipe that the child will read from
1 => array("pipe", "w"), // stdout is a pipe that the child will write to
2 => array("pipe", "w") // stderr
);
$process = proc_open("/usr/bin/dig $host +short A", $descriptorspec, $pipes);
if (is_resource($process)) {
// $pipes now looks like this:
// 0 => writeable handle connected to child stdin
// 1 => readable handle connected to child stdout
// 2 => readable handle
$ip = fgetsPending($pipes[1]);
fclose($pipes[0]);
fclose($pipes[1]);
fclose($pipes[2]);
// It is important that you close any pipes before calling
// proc_close in order to avoid a deadlock
proc_close($process);
}
return $ip;
}
function fgetsPending(&$in,$tv_sec=5)
{
if ( stream_select($read = array($in),$write=NULL,$except=NULL,$tv_sec) ) return fgets($in);
else return FALSE;
}
echo getip();