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 這並非內置的變量, 只是普通的一個變量名稱而已。爲何經過這樣處理,就能實現輸出重定向呢?php
因而只能google出stackoverflow答案 : https://stackoverflow.com/questions/6472102/redirecting-i-o-in-phplinux
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.google
解釋說:spa
若是你關閉了標準輸出,標準錯誤輸出文件描述符,那麼你打開的前三個文件描述符將成爲新的標準輸入、輸出、錯誤的描述符。命令行
使用$STDIN, $STDOUT純粹是障眼法而已, 必須指定爲全局變量,不然文件描述符將在函數執行完畢以後被釋放。指針
利用這個特性,後臺腳本運行時,就能夠直接輸出並被記錄到相關的文件中,給咱們跟蹤程序帶來極大的方便。code
意思是把標準錯誤流 (stdout) 、標準錯誤流(stderr)重定向到設備/dev/null上。blog
/dev/null 是類Unix系統中的一個特殊文件設備,他的做用是接受一切輸入它的數據並丟棄這些數據。一般被當作垃圾桶來用。three
將輸出流重定向到它上面,就是丟棄這個輸出流上的全部輸出。
嘗試從/dev/null讀取數據,會馬上獲得一個EOF。
順便,類Unix系統中,0表明標準輸入流(stdin),1表明標準輸出流(stdout),2表明標準錯誤流(stderr)。