曲径通幽论坛
标题:
read()与终端控制
[打印本页]
作者:
beyes
时间:
2009-3-15 10:54
标题:
read()与终端控制
以下代码主要测试read()调用与终端控制中的c_cc[VMIN]的情况:
#include <stdio.h>
#include <stdlib.h>
#include <termios.h>
#include <term.h>
#include <unistd.h>
#include <curses.h>
static
struct
termios initial_settings, new_settings;
int
main()
{
char
ch;
int
flag =
0
;
int
cnt =
0
;
tcgetattr(
0
, &initial_settings);
new_settings = initial_settings;
new_settings.c_lflag &= ~ICANON;
/*非标准模式*/
new_settings.c_cc[VMIN] =
5
;
/*接收5个字符后read才能返回*/
new_settings.c_cc[VTIME] =
0
;
/*对时间不作要求*/
tcsetattr(
0
, TCSANOW, &new_settings);
/*设置终端*/
while
(read(
0
, &ch,
1
) && ch !=
'q'
) {
/*其实这里read的返回值不会有0的情况*/
if
(!flag){
printf(
"
\n
"
);
/*输入完需要换行输出*/
flag =
1
;
}
printf(
"%c
\n
"
, ch);
cnt++;
if
( cnt == new_settings.c_cc[VMIN] ) {
/*全部输出完时恢复起始标志*/
cnt =
0
;
flag =
0
;
}
}
tcsetattr(
0
, TCSANOW, &initial_settings);
exit(
0
);
}
运行及输出
:
[root@localhost C]# ./read_test.exe
12345
1
2
3
4
5
dertq
d
e
r
t
在上面的 read() 调用中,其实不会遇到返回值为 0 的情况。因为终端的控制使得在输入字符没有达到 5 个时read()不会返回。也就是说,read() 在依次读取第一次输入的最后一个字符后,当再进行新一次读取时,由于此时终端还在等待 5 个字符的输入,所以read() 没有被返回,故 read() 不会存在什么都读不到而返回 0 的情况。
欢迎光临 曲径通幽论坛 (http://www.groad.net/bbs/)
Powered by Discuz! X3.2