【C語言實現串列埠通訊知識點整理(三)】串列埠開啟、設定資料成功後進行資料讀寫
阿新 • • 發佈:2018-11-11
int OpenDev(char *Dev)
{
int fd = open(Dev,O_RDWR | O_NOCTTY | O_NONBLOCK);
if(-1 == fd)
{
perror("Can't Open Serial Port");
return -1;
} else
{
printf("Open com success!!!!!!!!!!!");
return fd;
}
}
1.成功開啟串列埠後,得到一個檔案描述符fd,通過進行fd的讀寫實現通訊
2.傳送資料:write()函式
3.接收資料:read()函式
//=========================== 寫資料 ===================================== pthread_mutex_lock(&mutex_w); DebugLen = strlen(data.Debug); if((flag=write(fd,data.Debug,DebugLen)) != DebugLen) { printf("--------------1----------------%d\n",flag); printf("write error!!!\n"); } pthread_mutex_unlock(&mutex_w); //=========================== 讀資料 ===================================== pthread_mutex_lock(&mutex_r); nread = read(fd,Buff_BtoTV,30); //nread為read返回值:實際讀到的位元組數 pthread_mutex_unlock(&mutex_r);
注:
1.因為該專案在讀寫資料是針對同一個結構體,所以在讀寫操作時需要加互斥鎖,防止在讀寫操作發生衝突(讀的時候資料改變)
2.建議加異常處理,當沒有讀到資料或者資料讀取不完整的時候加上適當操作