[英]Input/Output error when reading from serial port in Unix
My configurations for the serial port is close to the one in this link: Serial-programming-HOWTO in the non-canonical input mode.我对串行端口的配置与此链接中的配置接近:非规范输入模式下的串行编程-HOWTO 。 This is my code where the problem happens:这是我发生问题的代码:
char buffer;
int received;
while (true) {
received = read(serial_com,
&buffer,
sizeof(buffer));
if (received < 0) {
perror("error reading") << endl;
cout << "error no." << errno;
//exit(1);
}
cout << buffer;
}
After I read one character, sometimes it returns the read character, and other times it gives me this error:在我读取一个字符后,有时它会返回读取的字符,有时它会给我这个错误:
error reading: Input/output error
error no.5
This error occurs as soon as I run the program.我一运行程序就会出现这个错误。 How can I fix this?我怎样才能解决这个问题?
I have also noticed that when I print the variable received
, it first prints 0
and then prints -1
and then it prints the error mentioned.我还注意到,当我打印变量received
时,它首先打印0
,然后打印-1
,然后打印提到的错误。
Most likely you are trying to read data faster, than it comes in - and if you try to read a character, when none is available, this is indeed an IO error.很可能您尝试读取数据的速度比输入数据的速度快 - 如果您尝试读取一个字符,当没有可用的字符时,这确实是 IO 错误。
You have a few possibilities:你有几种可能:
read()
call, until data is available使用阻塞模式(这将在read()
调用中冻结程序,直到数据可用select
to make sure you only try to read, if there is a character available使用select
确保您只尝试阅读,如果有可用的字符epoll
)使用特定于平台的机制(如epoll
)libev
) to abstract away these problems.使用库(如libev
)来抽象出这些问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.