在以下用于嵌入式设备的C程序中,我尝试显示一个点(".")每次用户在通过串行电缆连接到我的设备的远程计算机上,在她的终端程序上输入一些字符并按回车键时。
我看到的是,一旦检测到第一个回车符,printf就会在无限循环中显示点。我原以为FD_ZERO et FD_CLR会“重置”等待条件。
怎么做?
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
main()
{
int fd1; /* Input sources 1 and 2 */
fd_set readfs; /* File descriptor set */
int maxfd; /* Maximum file desciptor used */
int loop=1; /* Loop while TRUE */
/*
open_input_source opens a device, sets the port correctly, and
returns a file descriptor.
*/
fd1 = open("/dev/ttyS2", O_RDWR | O_NOCTTY | O_NONBLOCK);
if (fd1<0)
{
exit(0);
}
maxfd =fd1+1; /* Maximum bit entry (fd) to test. */
/* Loop for input */
while (loop)
{
FD_SET(fd1, &readfs); /* Set testing for source 1. */
/* Block until input becomes available. */
select(maxfd, &readfs, NULL, NULL, NULL);
if (FD_ISSET(fd1, &readfs))
{
/* input from source 1 available */
printf(".");
FD_CLR(fd1, &readfs);
FD_ZERO( &readfs);
}
}
}
发布于 2011-02-04 23:55:38
所有FD_CLR
和FD_ZERO
所做的只是重置fd_set,而不是清除底层条件。为此,您需要对所有数据执行read()
操作,直到不再有可用的数据。
实际上,如果您一次只想做一个fd,最好完全放弃select()
,只使用阻塞read()
来查看数据何时可用。
顺便说一句,FD_ZERO
和FD_CLR
做的事情是一样的,但是对于所有的fds。如果你做了其中一个,你就不需要另一个。
发布于 2011-02-04 23:53:04
首先,使用适当的函数头,如int main(void)
。其次,FD_SET
对存储fds有一个上限,换句话说,并不是所有的fds都可以用select
监控。(poll
没有这样的限制。)
第三,也是最后一点,在您的循环中,您只检查fd上是否有可用的数据,但您从未读取过这些数据。因此,它将在下一次迭代中继续可用。
https://stackoverflow.com/questions/4899855
复制相似问题