- 平台: Linux 3.2.0 x86 (Debian 7)
- 编译器: GCC 4.7.2 (Debian 4.7.2-5)
我正在编写一个函数,该函数从标准输入(stdin)读取单个字符,如果stdin中已经存在字符,则读取该字符。如果stdin为空,则函数不执行任何操作并返回-1。我搜索了非阻塞输入,并被指向poll()或select()。首先我尝试使用select(),但无法使其正常工作,因此我尝试了poll()并得出了同样的结论。我不确定这些函数具体做什么,但从我对poll()文档的理解来看,如果我像这样调用它:
struct pollfd pollfds;
pollfds = STDIN_FILENO;
pollfds.events = POLLIN;
poll(pollfds, 1, 0);
如果(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;
}