Linux C ++串口读/写

时间:2014-07-11 15:32:59

标签: c++ multithreading serial-port

我正在尝试读取我写入串口/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: %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()消息失败......”

感谢任何帮助 - 谢谢!

1 个答案:

答案 0 :(得分:1)

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

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

在这里阅读O_NONBLOCK标志: http://pubs.opengroup.org/onlinepubs/7908799/xsh/read.html