【发布时间】:2013-04-26 04:51:02
【问题描述】:
我搜索但没有得到这个问题的相关答案,我正在使用 linux 机器,我想检查标准输入流是否包含任何字符,而不从流中删除字符。
【问题讨论】:
-
C++ 还是 C?您的问题被标记为两者。
我搜索但没有得到这个问题的相关答案,我正在使用 linux 机器,我想检查标准输入流是否包含任何字符,而不从流中删除字符。
【问题讨论】:
cacho 在正确的路径上,但是 select 仅在您处理多个文件描述符时才需要,并且 stdin 不是 POSIX 文件描述符 (int);这是一个FILE *。如果你走那条路,你会想使用STDIN_FILENO。
这也不是一条非常干净的路线。我更喜欢使用poll。通过将 timeout 指定为 0,poll 将立即返回。
如果任何选定的文件上都没有发生任何定义的事件 描述符,poll() 应至少等待超时毫秒 在任何选定的文件描述符上发生的事件。 如果值 超时时间为 0,poll() 将立即返回。 如果值为 timeout 为 -1,poll() 将阻塞,直到发生请求的事件或 直到通话中断。
struct pollfd stdin_poll = { .fd = STDIN_FILENO
, .events = POLLIN | POLLRDBAND | POLLRDNORM | POLLPRI };
if (poll(&stdin_poll, 1, 0) == 1) {
/* Data waiting on stdin. Process it. */
}
/* Do other processing. */
【讨论】:
您可能想尝试select() 函数,并等待数据进入输入流。
说明:
select() 和 pselect() 允许程序监视多个文件 描述符,等到一个或多个文件描述符变为 为某种类型的 I/O 操作“准备好”(例如,可能的输入)。一份文件 如果可以执行描述符,则认为已准备好 相应的 I/O 操作(例如,read(2))而不阻塞。
在您的情况下,文件描述符将是 stdin
void yourFunction(){
fd_set fds;
struct timeval timeout;
int selectRetVal;
/* Set time limit you want to WAIT for the fdescriptor to have data,
or not( you can set it to ZERO if you want) */
timeout.tv_sec = 0;
timeout.tv_usec = 1;
/* Create a descriptor set containing our remote socket
(the one that connects with the remote troll at the client side). */
FD_ZERO(&fds);
FD_SET(stdin, &fds);
selectRetVal = select(sizeof(fds)*8, &fds, NULL, NULL, &timeout);
if (selectRetVal == -1) {
/* error occurred in select(), */
printf("select failed()\n");
} else if (selectRetVal == 0) {
printf("Timeout occurred!!! No data to fetch().\n");
//do some other stuff
} else {
/* The descriptor has data, fetch it. */
if (FD_ISSET(stdin, &fds)) {
//do whatever you want with the data
}
}
}
希望对你有帮助。
【讨论】:
0 而不是 stdin