我有一个工作程序来读取来自终端的数据。问题是,例如,当数据进入和停止时,我的程序会继续从缓冲区读取数据。如何阻止它阅读已通过端口传输的内容?
这是我的代码,也可以是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);
}
}
答案 0 :(得分:2)
O_NDELAY可防止读取阻塞。您应该始终检查返回代码。 Read将返回-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;
}