2017-08-12 17 views
1

我有一個基於終端的php程序,基本上只運行在一個大for循環中,做了一堆東西然後退出。我希望能夠中斷循環,暫停或退出應用程序。目前,我必須擊中^ C才能退出應用程序(或從另一個終端屏幕中刪除它)。任何想法我可能會實現這個?如何在PHP中實現「按Q隨時退出」

Running program... 
[Press Q to quit and <spacebar> to pause at any time] 
text 
text 
text 
... 
more text scrolling by 

我得到如何戒菸,如何暫停,那是很容易的,但我不知道如何監測輸入一邊做噸的其他功能。

非常感謝!

+1

[這可能](https://stackoverflow.com/questions/8308997/stop-executing-php-for-or-while-loop-在命令行中按鍵)幫助隊友...我相信他也許正在嘗試類似的東西。 – Samuel

+0

檢查https://stackoverflow.com/questions/3684367/php-cli-how-to-read-a-single-character-of-input-from-the-tty-without-waiting-f – Fawzan

回答

2

找到答案在這裏:Reading line by line from STDIN without blocking

感謝誰給了我一些搜索參數,以獲得正確的答案,最終上述評議。

的解決方案是在stream_set_blocking如下圖所示:

<?php 
    $stdin = fopen('php://stdin', 'r'); 
    stream_set_blocking ($stdin , 0); 

    for($x=0; $x <=10; $x++) { 
    echo "$x\n"; 

    $line = fgets($stdin); //Doesn't wait for input because blocking is turned off! 
    if (! empty($line)) { 
     die(); 
    } 
} 
?> 
+0

非常好的解決方案。 –