簡體   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