参考网址

(138条消息) 嵌入式linux:getchar() 非阻塞_起点的博客-CSDN博客_getchar 非阻塞

程序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
//由于getchar() 函数会一直阻塞,网上搜到下面的函数来实现非阻塞的读取。实际使用的时候只需要调用kbhit() 函数即可。其他函数没有看是什么意思
#include <stdio.h>
#include <string.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <termios.h>
#include <unistd.h>

static struct termios ori_attr, cur_attr;

static __inline int tty_reset(void)
{
if (tcsetattr(STDIN_FILENO, TCSANOW, &ori_attr) != 0)
return -1;

return 0;
}

static __inline int tty_set(void)
{

if (tcgetattr(STDIN_FILENO, &ori_attr))
return -1;

memcpy(&cur_attr, &ori_attr, sizeof(cur_attr));
cur_attr.c_lflag &= ~ICANON;
// cur_attr.c_lflag |= ECHO;
cur_attr.c_lflag &= ~ECHO;
cur_attr.c_cc[VMIN] = 1;
cur_attr.c_cc[VTIME] = 0;

if (tcsetattr(STDIN_FILENO, TCSANOW, &cur_attr) != 0)
return -1;

return 0;
}

static __inline int kbhit(void)
{

fd_set rfds;
struct timeval tv;
int retval;

/* Watch stdin (fd 0) to see when it has input. */
FD_ZERO(&rfds);
FD_SET(0, &rfds);
/* Wait up to five seconds. */
tv.tv_sec = 0;
tv.tv_usec = 0;

retval = select(1, &rfds, NULL, NULL, &tv);
/* Don't rely on the value of tv now! */

if (retval == -1)
{
perror("select()");
return 0;
}
else if (retval)
return 1;
/* FD_ISSET(0, &rfds) will be true. */
else
return 0;
return 0;
}

int main()
{
int tty_set_flag;
tty_set_flag = tty_set();
while (1)
{

if (kbhit())
{
const int key = getchar();
printf("%c pressed\n", key);
if (key == 'q')
break;
}
else
{
fprintf(stderr, "<no key detected>\n");
}
}

if (tty_set_flag == 0)
tty_reset();
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <stdio.h>
#include <termios.h>
#include <unistd.h>
#include <fcntl.h>

int kbhit(void)
{
struct termios oldt, newt;
int ch;
int oldf;
tcgetattr(STDIN_FILENO, &oldt);
newt = oldt;
newt.c_lflag &= ~(ICANON | ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &newt);
oldf = fcntl(STDIN_FILENO, F_GETFL, 0);
fcntl(STDIN_FILENO, F_SETFL, oldf | O_NONBLOCK);
ch = getchar();
tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
fcntl(STDIN_FILENO, F_SETFL, oldf);

if (ch != EOF)
{
ungetc(ch, stdin);
return 1;
}

return 0;
}

int main(void)

{
while(1)
{
if(kbhit())
{
printf("keyboard hit\n");
printf("%c\n", getchar());
}
else
{
printf("keyboard not hit\n");
}
}

return 0;
}