2013-11-23 55 views
0

我目前正在編寫一個C程序,寫入Mac OS X上的串行端口。我想使用POSIX API來使用Gnu/Linux上的代碼。我讀'Posix串行編程'來配置串行端口並寫入基本的讀/寫命令。在PROGRAMM如下:Mac OS X - 閱讀總是返回1

// 
// main.c 
// navilink 
// 
// Created by HEINRICH Yannick on 22/11/2013. 
// 
// 

#include <stdio.h> /* Standard input/output definitions */ 
#include <string.h> /* String function definitions */ 
#include <unistd.h> /* UNIX standard function definitions */ 
#include <fcntl.h> /* File control definitions */ 
#include <errno.h> /* Error number definitions */ 
#include <termios.h> /* POSIX terminal control definitions */ 
#include <sys/types.h> 
#include <sys/uio.h> 
#include "packetapi.h" 

int main(){ 


    int fd; 

    fd = open("/dev/tty.usbserial", O_RDWR | O_NOCTTY |O_NDELAY); 
    if(fd == -1) 
    { 
     perror("Unable to open port !"); 
    } 
    else 
    { 
     fcntl(fd, F_SETFL,0); 
    } 

    struct termios options; 

    tcgetattr(fd, &options); 

    cfsetispeed(&options, B115200); 
    cfsetospeed(&options, B115200); 

    options.c_cflag |= (CLOCAL | CREAD); 

    tcsetattr(fd, TCSANOW, &options); 


    options.c_cflag &= ~PARENB; 
    options.c_cflag &= ~CSTOPB; 
    options.c_cflag &= ~CSIZE; 
    options.c_cflag |= CS8; 

    options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); 

    options.c_iflag &= ~(IXON | IXOFF | IXANY); 


    options.c_oflag &= ~OPOST; 
    options.c_cc[VMIN] = 0; 
    options.c_cc[VTIME] = 10; 

    unsigned char * packet = YGCreatePacket(PID_SYNC, 0, 0); 

    write(fd, packet, 9); 


    unsigned char buffer[255], *ptrBuffer; 

    ptrBuffer = buffer; 
    ssize_t nbytes = 0; 
    while((nbytes = read(fd, buffer, buffer + sizeof(buffer) - ptrBuffer -1) > 0)) 
    { 
     ptrBuffer += nbytes; 
     if(ptrBuffer[-1] == PACK_END2 && ptrBuffer[-2] == PACK_END1) 
      break; 
    } 

    close(fd); 
    return 0; 

} 

我有我的OS(小牛),一個奇怪的現象,在這一部分:

unsigned char buffer[255], *ptrBuffer; 

    ptrBuffer = buffer; 
    ssize_t nbytes = 0; 
    while((nbytes = read(fd, buffer, buffer + sizeof(buffer) - ptrBuffer -1) > 0)) 
    { 
     ptrBuffer += nbytes; 
     if(ptrBuffer[-1] == PACK_END2 && ptrBuffer[-2] == PACK_END1) 
      break; 
    } 

當我使用調試器時,nbytes變量始終是1但是當我同時查看了buffer數組,它充滿了多於1個字節,read似乎沒有返回讀取的字節數...

這種方法有什麼問題?

+1

'read(fd,buffer,buffer + sizeof(buffer) - ptrBuffer -1)'應該是read(fd,ptrBuffer,buffer + sizeof(buffer) - ptrBuffer -1) ',對嗎? –

回答

2

使用這個代替(只有一個括號改變的地方 - 我假設的指針算術是有效的):

while((nbytes = read(fd, buffer, buffer + sizeof(buffer) - ptrBuffer -1)) > 0) 

與您的代碼,要存儲的比較結果爲nbytes,那將始終爲0或1.

+0

第二個參數應該是'bufferPtr',而不是'buffer',如上所述。 –

+0

我覺得很愚蠢,知道:)謝謝你揭示我這個巨大的錯誤! – yageek