我在Linux下使用下面的C代码从超时为2秒的串行调制解调器读取。它工作正常,除了我第一次尝试读取数据时它返回0字节读取。后续读取正确返回数据。可能有什么不对?
int readSerial(int fd, char *buffer, int length, int timeout_ms)
{
int i = 0;
struct timeval tv;
fd_set read_fd;
if (fd >= 0)
for (i = 0; i < length; i++)
do
{
if (timeout_ms >= 0)
{
tv.tv_sec = timeout_ms / MILLISECONDS_PER_SECOND;
tv.tv_usec = (timeout_ms % MILLISECONDS_PER_SECOND)
* MICROSECONDS_PER_MILLISECOND;
}
else //Wait forever
{
tv.tv_sec = FOREVER_POLLING_INTERVAL / MILLISECONDS_PER_SECOND;
tv.tv_usec = (FOREVER_POLLING_INTERVAL % MILLISECONDS_PER_SECOND)
* MICROSECONDS_PER_MILLISECOND;
}
FD_ZERO(&read_fd);
FD_SET(fd, &read_fd);
if (select(fd + 1, &read_fd, NULL, NULL, &tv) > 0)
{
char byte;
read(fd, &byte, sizeof(byte));
if (buffer)
*(buffer + i) = byte;
if (write(fd, &byte, 0) == -1) //detect unplugged USB device
{
close(fd);
return -1;
}
break;
}
else if (timeout_ms >= 0)
return i;
} while (timeout_ms < 0);
return i;
}