2012-09-21 128 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其他海报,但是这是回答你的要求。