2007年01月09日
exec, systemなでは標準出力と標準エラー出力を別々に扱ってくれない。
proc_openを使ってやると解決する。
▼コード
#!/usr/bin/php -q
<?php
function execWrap($command = "") {
$fd = array(
1 => array("pipe","w"),
2 => array("pipe","w"),
);
$stdout = array();
$stderr = array();
$code = null;
$process =proc_open($command, $fd, $pipes);
/* stdout */
while(!feof($pipes[1])) {
array_push($stdout, fgets($pipes[1]));
}
fclose($pipes[1]);
/* stderr */
while(!feof($pipes[2])) {
array_push($stderr, fgets($pipes[2]));
}
fclose($pipes[2]);
/* exit status code */
$code = proc_close($process);
return array('code' => $code, 'stdout' => $stdout, 'stderr' => $stderr);
}
print_r(execWrap("date"));
print_r(execWrap("date >&2"));
?>
▼実行結果
$ ./fd-test.php
Array
(
[code] => 0
[stdout] => Array
(
[0] => 2007年 1月 9日 火曜日 13:06:34 JST
[1] =>
)
[stderr] => Array
(
[0] =>
)
)
Array
(
[code] => 0
[stdout] => Array
(
[0] =>
)
[stderr] => Array
(
[0] => 2007年 1月 9日 火曜日 13:06:34 JST
[1] =>
)
)
無事、別々に取得出来た。
proc_openを使ってやると解決する。
▼コード
#!/usr/bin/php -q
<?php
function execWrap($command = "") {
$fd = array(
1 => array("pipe","w"),
2 => array("pipe","w"),
);
$stdout = array();
$stderr = array();
$code = null;
$process =proc_open($command, $fd, $pipes);
/* stdout */
while(!feof($pipes[1])) {
array_push($stdout, fgets($pipes[1]));
}
fclose($pipes[1]);
/* stderr */
while(!feof($pipes[2])) {
array_push($stderr, fgets($pipes[2]));
}
fclose($pipes[2]);
/* exit status code */
$code = proc_close($process);
return array('code' => $code, 'stdout' => $stdout, 'stderr' => $stderr);
}
print_r(execWrap("date"));
print_r(execWrap("date >&2"));
?>
▼実行結果
$ ./fd-test.php
Array
(
[code] => 0
[stdout] => Array
(
[0] => 2007年 1月 9日 火曜日 13:06:34 JST
[1] =>
)
[stderr] => Array
(
[0] =>
)
)
Array
(
[code] => 0
[stdout] => Array
(
[0] =>
)
[stderr] => Array
(
[0] => 2007年 1月 9日 火曜日 13:06:34 JST
[1] =>
)
)
無事、別々に取得出来た。