2016-09-29 88 views
0

我確實有一個奇怪的問題。我試圖在PHP中繞過輸出緩衝來運行system()調用並獲得即時輸出。它工作得很好,但出於某種奇怪的原因,「test.de」上的ping命令不會像google.de上的ping那樣呈現即時輸出。我確實在linux shell中立即看到了'ping test.de'的第一行,但它並沒有立即出現在這個腳本中。任何人都可以幫忙通過passthru()/ system()調用並輸出緩衝的PHP掛起問題

<?php 

    // Turn off output buffering 
    ini_set('output_buffering', 'off'); 
    // Turn off PHP output compression 
    ini_set('zlib.output_compression', false); 
    // Implicitly flush the buffer(s) 
    ini_set('implicit_flush', true); 
    ob_implicit_flush(true); 
    // Clear, and turn off output buffering 
    while (ob_get_level() > 0) { 
     // Get the curent level 
     $level = ob_get_level(); 
     // End the buffering 
     ob_end_clean(); 
     // If the current level has not changed, abort 
     if (ob_get_level() == $level) break; 
    } 
    // Disable apache output buffering/compression 
    if (function_exists('apache_setenv')) { 
     apache_setenv('no-gzip', '1'); 
     apache_setenv('dont-vary', '1'); 
    } 

    header('Cache-Control: no-cache'); 

    $i=0; 
    while($i < 1000) { 
    $i++; 
    echo '      '; 
    } 
    echo '<pre>'; 
    echo "Pinging google.de \n\n"; 
    passthru("ping -w 10 -c 4 google.de"); 
    echo "\n\nPinging test.de \n\n"; 
    passthru("ping -w 10 -c 4 test.de"); 
    echo '</pre>'; 
?> 

我標誌着這個輸出延遲線:

Pinging google.de 

PING google.de (172.217.16.131) 56(84) bytes of data. 
64 bytes from zrh04s06-in-f131.1e100.net (172.217.16.131): icmp_seq=1 ttl=56 time=22.0 ms 
64 bytes from zrh04s06-in-f131.1e100.net (172.217.16.131): icmp_seq=2 ttl=56 time=22.0 ms 
64 bytes from zrh04s06-in-f131.1e100.net (172.217.16.131): icmp_seq=3 ttl=56 time=22.2 ms 
64 bytes from zrh04s06-in-f3.1e100.net (172.217.16.131): icmp_seq=4 ttl=56 time=22.0 ms 

--- google.de ping statistics --- 
4 packets transmitted, 4 received, 0% packet loss, time 3004ms 
rtt min/avg/max/mdev = 22.016/22.067/22.200/0.130 ms 


Pinging test.de 

PING test.de (104.45.6.189) 56(84) bytes of data. <<<< THAT line is delayed!! 

--- test.de ping statistics --- 
11 packets transmitted, 0 received, 100% packet loss, time 9999ms 

回答

0

我想這是因爲你使用的是system()功能,因爲它只會返回最後一行。您可能更適合使用passthru()exec()函數。這裏是一個偉大的書面記錄上這些函數所做的和他們的區別:基於評論

您也可以嘗試追加輸出參數的shell腳本

https://stackoverflow.com/a/21016100/1789650

更新。將2>&1附加到行的末尾,它會將每個新的shell輸出行放入一個變量中。下面是它應該是什麼樣子:

exec("ping -w 10 -c 4 google.de 2>&1", $output); 
print_r($output); 
+0

**'EXEC()'**返回的最後一行 –

+0

我已經嘗試過'EXEC()'和'中繼()'。 exec()不適合直接輸出。 passthru()聽起來很合理,但它也不起作用。它產生了相同的延遲: - /我也嘗試了popen()並逐字節讀取STDOUT,但是這也不起作用。我也嘗試將輸出發送到一個文件(使用分離的控制檯),並在另一個進程正在寫入時執行system()調用來讀取該文件 - 但這也不起作用...我有點卡住了: -/ – xsign

+0

在命令後面添加一個'$ output'變量並打印到屏幕參數,用此信息更新答案... –