0

我正在使用一个不会终止的 while 循环,用于使用 C 代码复制 unix 的 Tail 命令。除了 Ctrl + C 之外,我需要一种方法来停止循环,这会退出我相信的过程。在代码中使用时有什么方法可以读取键盘命令?使用 getchar() 的问题在于它会停止循环运行,直到输入一个字符。这个问题有其他解决方案吗?

4

2 回答 2

2

You need to turn off blocking and line buffering. Turn off blocking so getc() returns right away. It will return -1 until it has a real character. Turn off line buffering so the OS sends the char right away instead of buffering it up until it has a full line which occurs when you press return.

#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;
}

I agree with the other posters that you should use signals, but this is the answer to what you asked.

于 2012-09-21T08:54:37.590 回答
0

这听起来很像comp.lang.c FAQ 中的这个问题

问:如何在不等待 RETURN 键的情况下从键盘读取单个字符?如何阻止字符在键入时在屏幕上回显?

于 2012-09-21T08:55:29.173 回答