今天在GitHub
主頁看到外國友人提了一個頗有意思的issue
,他在使用Co\System::exec()
執行了一個不存在的命令時,錯誤信息會直接打印到屏幕,而不是返回錯誤信息。php
實際上Swoole
提供的System::exec()
行爲上與PHP
的shell_exec
是徹底一致的,咱們寫一個shell_exec
的同步阻塞版本,執行後發現一樣拿不到標準錯誤流輸出的內容,會被直接打印到屏幕。shell
<?php $result = shell_exec('unknown'); var_dump($result);
htf@htf-ThinkPad-T470p:~/workspace/debug$ php s.php sh: 1: unknown: not found NULL htf@htf-ThinkPad-T470p:~/workspace/debug$
那麼如何解決這個問題呢?答案就是使用proc_open
+hook
實現。swoole
實例代碼
Swoole\Runtime::setHookFlags(SWOOLE_HOOK_ALL); Swoole\Coroutine\run(function () { $descriptorspec = array( 0 => array("pipe", "r"), 1 => array("pipe", "w"), 2 => array("pipe", "w"), ); $process = proc_open('unknown', $descriptorspec, $pipes); var_dump($pipes); var_dump(fread($pipes[2], 8192)); $return_value = proc_close($process); echo "command returned $return_value\n"; });
使用proc_open
,傳入了3
個描述信息:spa
fd
爲0
的流是標準輸入,能夠在主進程內向這個流寫入數據,子進程就能夠獲得數據fd
爲1
的流是標準輸出,這裏能夠獲得執行命令的輸出內容fd
爲2
的pipe stream
就是stderr
,讀取stderr
就能拿到錯誤信息輸出
使用fread
就能夠拿到標準錯誤流輸出的內容。.net
htf@htf-ThinkPad-T470p:~/workspace/swoole/examples/coroutine$ php proc_open.php array(3) { [0]=> resource(4) of type (stream) [1]=> resource(5) of type (stream) [2]=> resource(6) of type (stream) } string(26) "sh: 1: unknown: not found " command returned 32512 htf@htf-ThinkPad-T470p:~/workspace/swoole/examples/coroutine$
Swoole 正在參與 2020 年度 OSC 中國開源項目評選,請點擊下方連接投出您的一票,投票直達連接:https://www.oschina.net/p/swoole-serverdebug