linux c 非阻塞 键盘,C无阻塞键盘输入

小编典典

如前所述,您可以使用sigactionctrl-c select陷阱或任何标准输入。

但是请注意,使用后一种方法时,您还需要设置TTY,使其处于一次字符模式,而不是一次行模式。后者是默认设置-

如果您输入一行文本,则在您按Enter键之前,它不会发送到正在运行的程序的stdin中。

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

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

函数,kbhit()并且getch():

#include

#include

#include

#include

#include

struct termios orig_termios;

void reset_terminal_mode()

{

tcsetattr(0, TCSANOW, &orig_termios);

}

void set_conio_terminal_mode()

{

struct termios new_termios;

/* take two copies - one for now, one for later */

tcgetattr(0, &orig_termios);

memcpy(&new_termios, &orig_termios, sizeof(new_termios));

/* register cleanup handler, and set the new terminal mode */

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()) {

/* do some work */

}

(void)getch(); /* consume the character */

}

2020-06-02

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值