繁体   English   中英

Linux C ++串行端口读/写

[英]Linux C++ Serial Port Reading/Writing

我正在尝试读取已写入串行端口/tty/USBS0 我已经通过serial_fd = open(serialport.str().c_str(), O_RDWR | O_NOCTTY | O_NDELAY);打开了端口serial_fd = open(serialport.str().c_str(), O_RDWR | O_NOCTTY | O_NDELAY); ,并且我正在通过retVal2 = write(serial_fd, (void *)&msg, length);写入数据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: %s\n", 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: %s\n", strerror(errno));
        }
        totalBytes+=retVal;

    }

    if (msgHeader.startByte != START_BYTE) {
        printf("Bad start byte on message\n");
        continue;
    }
    else
    {
        printf("MSG RCV: StartByte=0x%X, Length=0x%X, ID=0x%X\n", msgHeader.startByte, msgHeader.ID, msgHeader.length);

        break;
    }
}
}

以上是我创建的线程; 但是,输出永远不会超过“范围测试-第一次循环”。 即使我在写入数据后显式调用了线程,结果也是相同的:它无限读取。 我知道它实际上是在读取,因为如果我在卡住的情况下断开电路板的连接,它将开始打印“ read()消息失败...”。

任何帮助表示赞赏-谢谢!

您可能需要在开放系统调用中设置O_NONBLOCK标志; 这样,根据写入端口的数据的不同,您将退出read()并退出错误/获取已填充的缓冲区。

“如果某个进程打开了要写入的管道,并且清除了O_NONBLOCK,则read()将阻塞调用线程,直到某些数据被写入或者所有打开了该管道以进行写入的进程关闭了该管道为止。”

在此处阅读有关O_NONBLOCK标志的信息: http : //pubs.opengroup.org/onlinepubs/7908799/xsh/read.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM