Linux serial port buffer not empty when opening device

前端 未结 1 1484
走了就别回头了
走了就别回头了 2021-01-13 21:41

I have a system where I am seeing strange behavior with the serial ports that I don\'t expect. I\'ve previously seen this on occasion with usb-to-serial adapters, but now I\

相关标签:
1条回答
  • 2021-01-13 22:36

    The Linux terminal driver buffers input even if it is not opened. This can be a useful feature, especially if the speed/parity/etc. are set appropriately.

    To replicate the behavior of lesser operating systems, read all pending input from the port as soon as it is open:

    ...
    int fd = open ("/dev/ttyS0", O_RDWR | O_NOCTTY | O_SYNC);
    if (fd < 0)
            exit (1);
    
    set_blocking (fd, 0);   // disable reads blocked when no input ready
    
    char buf [10000];
    int n;
    do {
            n = read (fd, buf, sizeof buf);
    } while (n > 0);
    
    set_blocking (fd, 1);  // enable read blocking (if desired)
    
    ...  // now there is no pending input
    
    
    
    void set_blocking (int fd, int should_block)
    {
            struct termios tty;
            memset (&tty, 0, sizeof tty);
            if (tcgetattr (fd, &tty) != 0)
            {
                    error ("error %d getting term settings set_blocking", errno);
                    return;
            }
    
            tty.c_cc[VMIN]  = should_block ? 1 : 0;
            tty.c_cc[VTIME] = should_block ? 5 : 0; // 0.5 seconds read timeout
    
            if (tcsetattr (fd, TCSANOW, &tty) != 0)
                    error ("error setting term %sblocking", should_block ? "" : "no");
    }
    
    0 讨论(0)
提交回复
热议问题