我需要在Linux上的串行端口或套接字上等待n个字节的数据(计数已知)。 目前我使用一个循环与调查,测量时间和减少超时:C:在超时的阻塞套接字上等待n个字符
static int int_read_poll(int fd, uint8_t *buffer, size_t count, int timeout)
{
struct pollfd pfd;
int rc;
pfd.fd = fd;
pfd.events = POLLIN;
rc = poll(&pfd, 1, timeout);
if (rc < 0) {
perror("poll");
return 0;
}
if (rc > 0) {
if (pfd.revents & POLLIN) {
rc = read(fd, buffer, count);
return rc;
}
}
return 0;
}
static int int_read_waitfor(int fd, uint8_t *buffer, size_t count, int timeout)
{
int rc;
struct timespec start, end;
int delta_ms;
int recv = 0;
do {
clock_gettime(CLOCK_MONOTONIC_RAW, &start);
rc = int_read_poll(fd, buffer + recv, count - recv, timeout);
clock_gettime(CLOCK_MONOTONIC_RAW, &end);
delta_ms = (end.tv_nsec - start.tv_nsec)/1000000;
if (!rc || (rc < 0)) return 0;
recv += rc;
timeout -= delta_ms;
if (timeout <= 0)
return 0;
} while (recv != count);
return recv;
}
上的串行端口,每个单字节poll返回,并导致多次迭代。
有没有更好的方法来解决这个问题?
我知道,根据波特率,超时可能不会在该代码部分递减。计数纳秒可能是更好的方法。
在一些串行命令我的示例应用程序,以前的代码共有272个系统调用,新的版本仅使用142 –