栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

C无阻塞键盘输入

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C无阻塞键盘输入

如前所述,您可以使用

sigaction
ctrl-c
select
陷阱或任何标准输入。

但是请注意,使用后一种方法时,您还需要设置TTY,使其处于一次字符模式,而不是一次行模式。后者是默认设置-
如果您输入一行文本,则在您按Enter键之前,它不会发送到正在运行的程序的stdin中。

您需要使用该

tcsetattr()
功能关闭ICANON模式,并且可能也禁用ECHO。从内存中,您还必须在程序退出时将终端设置回ICANON模式!

为了完整起见,这里有一些我刚刚删除的代码(nb:没有错误检查!),它设置了Unix TTY并模拟DOS

<conio.h>
函数,
kbhit()
并且
getch()

#include <stdlib.h>#include <string.h>#include <unistd.h>#include <sys/select.h>#include <termios.h>struct termios orig_termios;void reset_terminal_mode(){    tcsetattr(0, TCSANOW, &orig_termios);}void set_conio_terminal_mode(){    struct termios new_termios;        tcgetattr(0, &orig_termios);    memcpy(&new_termios, &orig_termios, sizeof(new_termios));        atexit(reset_terminal_mode);    cfmakeraw(&new_termios);    tcsetattr(0, TCSANOW, &new_termios);}int kbhit(){    struct timeval tv = { 0L, 0L };    fd_set fds;    FD_ZERO(&fds);    FD_SET(0, &fds);    return select(1, &fds, NULL, NULL, &tv);}int getch(){    int r;    unsigned char c;    if ((r = read(0, &c, sizeof(c))) < 0) {        return r;    } else {        return c;    }}int main(int argc, char *argv[]){    set_conio_terminal_mode();    while (!kbhit()) {            }    (void)getch(); }


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/415424.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号