2012-09-21 59 views
0

我正在使用while循環,它不終止,用於使用C代碼重新生成unix的尾部命令。我需要一種方法來停止Ctrl + C之外的循環,這會退出我相信的過程。在代碼中使用時是否有任何方法可以讀取鍵盤命令?使用getchar()的問題是,它會阻止循環運行,直到輸入一個字符。這個問題有其他解決方案嗎?在循環中讀取停止信號

+0

您確定要讓程序互動嗎?請參閱http://fmg-www.cs.ucla.edu/geoff/interfaces.html#interactive –

+2

您可以簡單地捕獲ctrl-c(sigint)。 – Macmade

+1

你應該閱讀關於Unix信號處理....從[this](http://www.yolinux.com/TUTORIALS/C++Signals.html)得到一個想法 – shan

回答

2

您需要關閉阻塞和行緩衝。關閉阻擋,因此getc()立即返回。它會返回-1,直到它有一個真實的字符。關閉行緩衝,以便操作系統立即發送字符,而不是緩衝它,直到您按下回車時出現全行。

#include <unistd.h> /* UNIX standard function definitions */ 
#include <fcntl.h> /* File control definitions */ 
#include <termios.h> /* POSIX terminal control definitions */ 

int main(void) { 

    // Turn off blocking 
    fcntl(STDIN_FILENO, F_SETFL, O_NONBLOCK); 

    struct termios options, oldoptions; 
    tcgetattr(STDIN_FILENO, &options); 
    // Disable line buffering 
    options.c_lflag &= ~(ICANON); 

    // Set the new options for the port... 
    tcsetattr(STDIN_FILENO, TCSANOW, &options); 

    while(1) { 
     char c = getc(stdin); 
     if(c != -1) break; 
    } 

    // Make sure you restore the options otherwise you terminal will be messed up when you exit 
    tcsetattr(STDIN_FILENO, TCSANOW, &oldoptions); 

    return 0; 
} 

我同意,你應該使用signals其他海報,但是這是回答你的要求。