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;
}
、世論調査では、各単一バイトに返し、多くの反復が発生します。
この問題を解決するためのより洗練された方法がありますか?
ボーレートによっては、タイムアウトがそのコード部分で減少しないことがあります。ナノ秒を数えるほうが良いアプローチかもしれません。
いくつかのシリアルコマンドを使用した私のサンプルアプリケーションでは、前のコードでは合計272のシステムコールが使用されました。 –