2007年01月09日

PHPで終了コード・標準出力・標準エラー出力を扱う

livedoorClipに登録 | このエントリーをはてなブックマークに追加 | del.icio.usに登録 | MM/Memoに登録

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] =>
)

)



無事、別々に取得出来た。


半袖 at 13:10│Comments(0)TrackBack(0)PHP 

トラックバックURL

この記事にコメントする

名前:
URL:
  情報を記憶: 評価: 顔