Linux串口I / O问题

时间:2011-02-04 15:42:41

标签: linux embedded serial-port

在以下嵌入式设备的C程序中,每次用户通过串行电缆连接到我的设备的远程计算机上的用户输入终端程序中的某些字符时,我都会尝试显示一个点(“。”)然后点击ENTER键。

我所看到的是,一旦检测到第一次回车,printf就会以无限循环显示点。我期待FD_ZERO和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);
        }
    }
}

2 个答案:

答案 0 :(得分:4)

所有FD_CLRFD_ZERO都会重置fd_set,但不会清除基础条件。为此,您需要read()所有数据,直到没有任何数据为止。

事实上,如果你只想一次做一个fd,你最好完全放弃select(),只需使用阻止read()来查看数据何时可用。< / p>

在旁注中,FD_ZEROFD_CLR的功能相同,但适用于所有fds。如果你做了一个,你就不需要另一个了。

答案 1 :(得分:1)

首先,使用int main(void)之类的正确函数标题。其次,FD_SET具有存储fds的上限,换句话说,并非所有fds都可以使用select进行监控。 (poll没有此限制。)

第三个也是最后一个,在你的循环中,你只检查fd上是否有可用数据,但你从来没有读过它。因此,它将继续在下一次迭代中可用。

相关问题