首页 > 开发 > linux > 正文

怎么在重定向标准输入后无阻塞的获取终端按键(在linux下用c语言实现)?

2017-09-11 20:33:11  来源: 网友分享

在实现more命令时所遇到的问题

未考虑重定向前,无阻塞的获取终端按键是如下代码所示实现的

    fp_tty = fopen("/dev/tty", "rw");    //更改终端属性,使字符立即输入且不显示    tcgetattr(0, &oldt);    newt = oldt;    newt.c_lflag &= ~( ICANON | ECHO );    tcsetattr(0, TCSANOW, &newt);    int ch = fgetc(fp_tty);

重定向后发现fp_tty始终为NULL

解决方案

代码如下:

#include <stdio.h>#include <fcntl.h>#include <termios.h>#include <unistd.h>int main(){    char ch;    //打开控制终端    int tty = open("/dev/tty", O_RDONLY);    struct termios newt, oldt;    //获取终端属性    tcgetattr(tty, &oldt);    newt = oldt;    //设置字符不缓冲且不回显    newt.c_lflag &= ~( ICANON | ECHO );    tcsetattr(tty, TCSANOW, &newt);    while (1) {        read(tty, &ch, 1);        if (ch == 'q') {            //还原终端属性            tcsetattr(tty, TCSANOW, &oldt);            fprintf(stderr, "Quit\n", ch);            break;        } else {            fprintf(stderr, "[%c]\n", ch);        }    }    return 0;}