我目前正在編寫一個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
似乎沒有返回讀取的字節數...
這種方法有什麼問題?
'read(fd,buffer,buffer + sizeof(buffer) - ptrBuffer -1)'應該是read(fd,ptrBuffer,buffer + sizeof(buffer) - ptrBuffer -1) ',對嗎? –