WorkerMan源码分析(resetStd方法,PHP中STDIN, STDOUT, STDERR的重定向)
?
WorkerMan中work.php中?resetStd 方法中代碼如下
public static function resetStd(){if (!static::$daemonize || static::$_OS !== 'linux') {return;}global $STDOUT, $STDERR;$handle = fopen(static::$stdoutFile, "a");if ($handle) {unset($handle);//關閉標準輸出和標準錯誤@fclose(STDOUT);@fclose(STDERR);//a 寫入方式打開,將文件指針指向文件末尾。如果文件不存在則嘗試創建之。//把標準輸出和錯誤 定位到 /dev/null$STDOUT = fopen(static::$stdoutFile, "a");$STDERR = fopen(static::$stdoutFile, "a");} else {throw new Exception('can not open stdoutFile ' . static::$stdoutFile);}}命令行下運行以上程序,將不會在控制臺輸出任何內容,輸出內容將被重定向到/dev/null中,非常詫異,一直不理解。$STDOUT, $STDERR?這并不是內置的變量,?只是普通的一個變量名稱而已。為什么通過這樣處理,就能實現輸出重定向呢?
于是只能google出stackoverflow答案 :?https://stackoverflow.com/questions/6472102/redirecting-i-o-in-php
fclose(STDIN); fclose(STDOUT); fclose(STDERR);$STDIN = fopen("/tmp/some-named-pipe", "r"); $STDOUT = fopen("/tmp/foo.out", "wb"); $STDERR = fopen("/tmp/foo.err", "wb");because when you close the standard input, output and error file descriptors, the first three new descriptors will become the NEW standard input, output and error file descriptors.
In my example here I redirected standard input to /dev/null and the output and error file descriptors to log files. This is common practice when making a daemon script in PHP.
解釋說:
如果你關閉了標準輸出,標準錯誤輸出文件描述符,那么你打開的前三個文件描述符將成為新的標準輸入、輸出、錯誤的描述符。
使用$STDIN, $STDOUT純粹是障眼法而已,?必須指定為全局變量,否則文件描述符將在函數執行完畢之后被釋放。
利用這個特性,后臺腳本運行時,就可以直接輸出并被記錄到相關的文件中,給我們跟蹤程序帶來極大的方便。
?
通過上面的答案再來理解resetStd方法
意思是把標準錯誤流 (stdout) 、標準錯誤流(stderr)重定向到設備/dev/null上。
/dev/null 是類Unix系統中的一個特殊文件設備,他的作用是接受一切輸入它的數據并丟棄這些數據。通常被當做垃圾桶來用。
將輸出流重定向到它上面,就是丟棄這個輸出流上的所有輸出。
嘗試從/dev/null讀取數據,會立刻得到一個EOF。
順便,類Unix系統中,0代表標準輸入流(stdin),1代表標準輸出流(stdout),2代表標準錯誤流(stderr)。轉載于:https://www.cnblogs.com/loveyouyou616/p/8880769.html
總結
以上是生活随笔為你收集整理的WorkerMan源码分析(resetStd方法,PHP中STDIN, STDOUT, STDERR的重定向)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: visual studio 2013 编
- 下一篇: php传入参数