【发布时间】:2013-12-14 20:40:03
【问题描述】:
- 平台:Linux 3.2.0 x86 (Debian 7)
- 编译器:GCC 4.7.2 (Debian 4.7.2-5)
如果字符已经存在于标准输入中,我正在编写一个从标准输入读取单个字符的函数。如果 stdin 为空,则该函数假定什么都不做并返回 -1。我搜索了非阻塞输入,并被指向poll() 或select()。首先我尝试使用 select() 但我无法让它工作,所以我尝试了 poll() 并得出了相同的结论。我不确定这些函数究竟做了什么,但根据我对 poll() 文档的理解,如果我这样称呼它:
struct pollfd pollfds;
pollfds = STDIN_FILENO;
pollfds.events = POLLIN;
poll(pollfds, 1, 0);
if(pollfds.revents & POLLIN) 如果“可以不阻塞地读取高优先级数据以外的数据”,则为真。但是 poll() 在我的测试情况下总是超时。我如何测试功能可能是问题,但我想要的功能正是我正在测试的。这是目前的功能和测试情况。
#include <poll.h>
#include <stdio.h>
#include <unistd.h>
int ngetc(char *c)
{
struct pollfd pollfds;
pollfds.fd = STDIN_FILENO;
pollfds.events = POLLIN;
poll(&pollfds, 1, 0);
if(pollfds.revents & POLLIN)
{
//Bonus points to the persons that can tell me if
//read() will change the value of '*c' if an error
//occurs during the read
read(STDIN_FILENO, c, 1);
return 0;
}
else return -1;
}
//Test Situation:
//Try to read a character left in stdin by an fgets() call
int main()
{
int ret = 0;
char c = 0;
char str[256];
//Make sure to enter more than 2 characters so that the excess
//is left in stdin by fgets()
fgets(str, 2, stdin);
ret = ngetc(&c);
printf("ret = %i\nc = %c\n", ret, c);
return 0;
}
【问题讨论】:
-
你的函数永远不会返回 0 : if ( ... ) return errno;否则返回 EWOULDBLOCK; ;那么最后的回报有什么用?
-
@philippelhardy 如果在读取过程中发生错误,该函数将返回 errno,但如果在读取过程中未发生错误,该函数将返回 0。该语句首先检查 stdin 中是否有数据如果没有数据,则调用 read() 之前的语句短路,但如果 stdin 中有数据,则调用 read(),如果 read() 返回 -1,则发生读取错误,因此返回 errno,否则如果未发生读取错误则条件为假,因此返回 0。
-
我的意思是:看起来最后一个 return 0 只是一个无法访问的代码,因为 if () return A;否则返回 B;模式。
-
哦,是的,我知道你的意思它看起来有点尴尬