在循环内读取停止信号

时间:2012-09-21 08:00:24

标签: c unix

我正在使用一个不会终止的while循环,用于使用C代码重现unix的Tail命令。我需要一种方法来阻止循环离开Ctrl + C,退出我相信的过程。在代码中使用时,有没有办法读取键盘命令?使用getchar()的问题是它会阻止循环运行,直到输入char。这个问题还有其他解决办法吗?

2 个答案:

答案 0 :(得分:2)

您需要关闭阻止和线路缓冲。关闭阻止,以便getc()立即返回。它将返回-1,直到它具有真实角色。关闭行缓冲,以便操作系统立即发送char而不是缓冲它,直到它按下返回时出现一个完整的行。

#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的其他海报,但这就是你问的答案。

答案 1 :(得分:0)

这听起来非常像this question from the comp.lang.c FAQ

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