Linux串行端口I/O问题

Linux串行端口I/O问题,linux,embedded,serial-port,Linux,Embedded,Serial Port,在下面的嵌入式设备C程序中,我试图显示一个点。每次用户在通过串行电缆连接到我的设备的远程计算机上,在其终端程序上输入一些字符并按下ENTER键时 我所看到的是,一旦检测到第一次回车,printf就会在无限循环中显示点。我希望FD_ZERO et FD_CLR重置等待条件 怎么做 #include <sys/time.h> #include <sys/types.h> #include <unistd.h> #include <stdio.h> #i

在下面的嵌入式设备C程序中,我试图显示一个点。每次用户在通过串行电缆连接到我的设备的远程计算机上,在其终端程序上输入一些字符并按下ENTER键时

我所看到的是,一旦检测到第一次回车,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);
        }
    }
}

首先,使用适当的函数头,如int mainvoid。其次,FD_SET有一个存储FD的上限,换句话说,并非所有FD都可以通过select进行监控。民意测验没有这样的限制

第三,也是最后一点,在循环中,您只检查fd上是否有可用数据,但从不读取。因此,它将在下一次迭代中继续可用。

所有FD_CLR和FD_ZERO do都将重置FD_集合,但不会清除基础条件。要做到这一点,您需要读取所有数据,直到不再有可用数据为止

事实上,若您一次只想执行一个fd,那个么最好完全不用select,只使用阻塞读取来查看数据何时可用


另一方面,FD_ZERO的作用与FD_CLR相同,但适用于所有FD。如果执行一个,则不需要另一个。

是否尝试查看select?的返回值,并且下一次循环迭代会再次设置FD_,撤消FD_CLR。并且不要忘记在每次printf之后执行fflushstdout,否则很长一段时间内都看不到该点。