c - 如何阻止我的程序读取串行端口缓冲区?

标签 c serial-port

我有一个工作程序来读取来自终端的数据。问题是,例如,当数据到来并停止时,我的程序继续从缓冲区读取。我怎样才能阻止它读取已经通过端口发送的内容?

这是我的代码,也可以是found at pastebin

#include <ncurses.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <fcntl.h>
#include <errno.h>
#include <termios.h>
#include <signal.h>
#include <unistd.h>
#include <iostream>
#include <signal.h>


int open_port(void);

int main()
{
    char dato[1];
    int fd = 0;
    fd = open_port();
    while(1)
    {
        read(fd,dato,1);
        //~ if(dato == "B")
        //~ return 0;
        printf(dato);
    }
}

int open_port(void)
{
    int fd; /* File descriptor for the port */  

    //~ fd = open("/home/tomas/ttySV1", O_RDWR | O_NOCTTY | O_NDELAY);
    fd = open("/dev/ttyUSB0", O_RDWR | O_NDELAY);
    //~ fd = open("/dev/ttyUSB0", O_RDWR);

    if (fd == -1)
    { 
        perror("open_port: No se pudo abrir el puerto: ");
    }
    else
    {
        struct termios options;

        /*
         * Get the current options for the port...
         */

        tcgetattr(fd, &options);

        /*
         * Set the baud rates to B9600...
         */

        cfsetispeed(&options, B9600);
        cfsetispeed(&options, B9600);

        /*
         * Enable the receiver and set local mode...
         */

        options.c_cflag |= (CLOCAL | CREAD);

        /*
         * Set the new options for the port...
         */

        tcsetattr(fd, TCSANOW, &options);

        options.c_cflag &= ~CSIZE; /* Mask the character size bits */
        options.c_cflag |= CS8;    /* Select 8 data bits */

        options.c_cflag &= ~PARENB;
        options.c_cflag &= ~CSTOPB;
        options.c_cflag &= ~CSIZE;
        options.c_cflag |= CS8;

        //~ fcntl(fd, F_SETFL, 0);
        return (fd);
    }
}

最佳答案

O_NDELAY 防止读取阻塞。您应该始终检查返回代码。读取将返回 -1 并将 errno 设置为 EWOULDBLOCK。

因此,请使用返回代码和 errno 来弄清楚该怎么做 - 例如:

ssize_t retval=1;
int doit=1;
while(doit)
{
 while( retval==1)
 {
    retval=read(fd, &ch, 1);
 }
 if(retval == -1)
 {
  if (errno == EWOULDBLOCK)
  {
      sleep 1;    
  }
  else
     doit=0;
}

关于c - 如何阻止我的程序读取串行端口缓冲区?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4115185/

相关文章:

c - Lex:识别文件中的数据类型

c - 警告 : implicit declaration of function 'Min' is invalid in C99 [-Wimplicit-function-declaration]

c++ - 新创建的暂停进程的 EIP 仅在 Windows XP 上失败 - kernel32.dll 镜像下的 EIP?

serial-port - 串口RS232与USB编程有什么区别?

Python 串行写入 Arduino 与 Arduino 串行监视器串行写入不同

c++ - 当其他线程正在等待读取时,写入串行端口将永远阻塞

C 串行通信。 WriteFile 成功,但我的设备仅处理第一个字符

c - ntohl 在 sin_port 上使用并得到负数

windows - 串口数据损坏的异常模式

c - 将 C 库与 Java、Ruby、Node、Python、Go、.NET 集成