Linux c++串口读写
Linux C++ Serial Port Reading/Writing
我正试图读取我已写入串行端口/tty/USBS0
的数据。我已经通过serial_fd = open(serialport.str().c_str(), O_RDWR | O_NOCTTY | O_NDELAY);
打开端口,我正在通过retVal2 = write(serial_fd, (void *)&msg, length);
写入数据。
然而,我遇到了一个问题,当我调用read()时,它停在那里;换句话说,它无限地继续读取。
void cmgGSP::read_thread(){
unsigned char msg[256];
unsigned char messagelength;
msg_header msgHeader; //msg_header is defined in cmgCOM.h
msgHeader.startByte = 0;
msgHeader.length = 0;
msgHeader.ID = 0;
int totalBytes;
int retVal;
cout<<"Scope Test -- In Read Thread"<<endl;
while(1) //infinte loop, since we're going to want to always be reading command data
{
cout<<"Scope Test -- In While(1)"<< endl;
totalBytes = 0;
while (totalBytes == 0) {
cout<<"Scope Test -- First While Loop"<<endl;
retVal = read(serial_fd, (unsigned char*)&msgHeader, 1);
cout<<"retVal: "<<retVal <<endl; //This does not get printed
if (retVal == -1)
{
printf("read() message failed: %sn", strerror(errno));
}
if (msgHeader.startByte != FROM_CMG) {
printf("Bad start byte on read()n");
totalBytes = 0;
} else {
cout<<"scope test 2"<<endl;
totalBytes+=retVal;
}
}
while (totalBytes < sizeof(msgHeader)) {
retVal = read(serial_fd, (unsigned char*)&msgHeader+totalBytes, sizeof(msgHeader)-totalBytes);
cout<< "in second while"<<endl;
if (retVal == -1){
printf("read() message failed: %sn", strerror(errno));
}
totalBytes+=retVal;
}
if (msgHeader.startByte != START_BYTE) {
printf("Bad start byte on messagen");
continue;
}
else
{
printf("MSG RCV: StartByte=0x%X, Length=0x%X, ID=0x%Xn", msgHeader.startByte, msgHeader.ID, msgHeader.length);
break;
}
}
}
上面是我创建的线程;然而,输出从来没有通过"Scope Test—First While循环"。即使在写入数据后显式地调用线程,结果也是一样的:它无限地读取。我知道它实际上正在阅读,因为如果我断开电路板,而它卡住了,它开始打印"read()消息失败……"
任何帮助是感激-谢谢!
您可能需要在开放系统调用中设置O_NONBLOCK标志;这样,根据写入端口的数据,您将退出read()并错误输出/获得已填满的缓冲区。
"如果某个进程打开了用于写的管道并且O_NONBLOCK被清除,read()将阻塞调用线程,直到一些数据被写入或管道被所有打开管道用于写的进程关闭。"
在这里阅读O_NONBLOCK标志:http://pubs.opengroup.org/onlinepubs/7908799/xsh/read.html
相关文章:
- 用C++快速读写文件
- 如何将图像传输到c++(dll)中的缓冲区,然后在c#的缓冲区中读/写
- 如何在信号处理程序和普通函数中对全局变量进行互斥读写操作
- 在一个读写器队列中,我可以用volatile替换原子吗
- C++套接字对不读/写父/子
- 如何调试读写器锁的死锁?
- 在两个线程上读/写 64 位,无互斥/锁定/原子
- Linux 挂载使用重新挂载以允许读写
- C++中读/写二进制文件
- 为什么我要从串口读取垃圾?
- 如何读/写或遍历 std::array 中的特定元素范围?
- Boost::Asio串行读/写打开:参数不正确
- Qt串口,当我写的时候,我看不懂我写的东西
- 在 C++ 的 USB 端口上读/写
- 无法将简单的读/写串口代码从 boost::asio::serial_port 迁移到 QSerialPort
- 使用C/C++和LibSerial在Ubuntu的串行端口上读写
- 串口写成功,读失败
- Linux下c++中的串口.可以读和写串行端口同时发生
- Linux c++串口读写
- 在linux上,串行端口在第一对读写之后挂起