我正在编写一个写入Mac OS X上串行端口的C程序。我想使用Posix API来使用Gnu / Linux上的代码。我阅读了'Posix Serial Programming'来配置串口并写入基本的读/写命令。该计划如下:
//
// 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;
}
我的操作系统(Mavericks)有一个奇怪的行为,在这一部分:
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个字节,{ {1}}似乎没有返回读取的字节数...
这种方法有什么问题?
答案 0 :(得分:2)
使用它(只改变了一个地方 - 我假设指针算术有效):
while((nbytes = read(fd, buffer, buffer + sizeof(buffer) - ptrBuffer -1)) > 0)
使用您的代码,您将比较结果存储到nbytes
,并且该值始终为0或1。