2016-04-26 60 views
0

我剛開始一個項目,我從現在開始一直在掙扎着關於串行端口的項目。我寫了一個靜態庫,它可以處理所有的串行例程,併爲「readLine()」和「writeLine()」函數提供一個接口。 除非從服務器在獲取數據後沒有啓動,否則所有內容在寫和讀過程中都是完美無缺的,除非數據被獲取後,數據將被髮回給我,然後我讀取它。閱讀串行端口返回我剛剛寫的

我用O_NDELAY打開我的fd並將我的讀系統調用配置爲非阻塞fcntl。

這裏是兩個線程循環,完美的工作。

void *Serial_Port::readLoop(void *param) 
{ 
    Serial_Port *sp = static_cast<Serial_Port*>(param); 
    std::string *line = NULL; 
    char buffer[128]; 

    while (1) 
    { 
     line = new std::string(); 
     while ((line->find("\r\n")) == std::string::npos) 
     { 
      usleep(100); 
      bzero(buffer, 128); 
      pthread_mutex_lock(sp->getRLock()); 
      if (read(sp->getDescriptor(), buffer, 127) > 0) 
      *line += buffer; 
      pthread_mutex_unlock(sp->getRLock()); 
     } 
     pthread_mutex_lock(sp->getRLock()); 
     sp->getRStack()->push(line->substr(0, line->find("\r\n"))); 
     pthread_mutex_unlock(sp->getRLock()); 
     delete (line); 
    } 
    return (param); 
} 

void *Serial_Port::writeLoop(void *param) 
{ 
    Serial_Port *sp = static_cast<Serial_Port*>(param); 
    std::string *line; 

    while (1) 
    { 
     line = NULL; 
     pthread_mutex_lock(sp->getWLock()); 
     if (!sp->getWStack()->empty()) 
     { 
      line = new std::string(sp->getWStack()->front()); 
      sp->getWStack()->pop(); 
     } 
     pthread_mutex_unlock(sp->getWLock()); 
     if (line != NULL) 
     { 
      pthread_mutex_lock(sp->getWLock()); 
      write(sp->getDescriptor(), line->c_str(), line->length()); 
      // fsync(sp->getDescriptor());                                                          
      pthread_mutex_unlock(sp->getWLock()); 
     } 
     usleep(100); 
    } 
    return (param); 
} 

我試圖刷新文件描述符,但我不能設法接收任何數據後,這樣做。我怎樣才能擺脫那些重複的,不必要的數據?

感謝。

+0

你禁用本地回聲? *「配置我的讀系統調用爲非阻塞」* - 可能是一個壞主意,因爲你似乎只是在延遲和輪詢中浪費更多的CPU週期。從終端讀取行,請參閱http://stackoverflow.com/questions/36586137/stop-on-newline-when-using-read/36588517#36588517 – sawdust

+0

我被迫把讀取在非阻塞模式,因爲它不會只要沒有東西可讀,就可以釋放互斥鎖。我沒有想過任何其他替代方法 – stalker2106

回答

1

經過多次試驗和行爲分析,我發現這是「Pulsar3」那不停地給我收回我發送的「確認」(在我使用的串行設備)。很高興知道!

+1

這在連接到CRT的串行設備中非常常見。按照慣例,CRT不會顯示您在鍵盤上輸入的內容,因此遠程系統有責任將其回顯給您,以便您可以看到它。 –

相關問題