java串口监听超时_从串口读取时如何实现read()的超时(C / C)
有幾種可能的方法 . 如果程序最終將定時多個i / o操作, select() 是明智的選擇 .
但是,如果唯一的輸入來自此i / o,則選擇非阻塞i / o和時序是一種簡單的方法 . 我已經將它從單字符i / o擴展到多字符,使其成為一個更普遍的完整示例:
#include
#include
#include
#include
int main(void)
{
int fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NDELAY); // sometimes "O_NONBLOCK"
char buf[10];
int done = 0, inbuf = 0;
struct timeval start, now;
gettimeofday (&start, NULL);
while (!done)
{
int bytesRead = read(fd, &buf[inbuf], sizeof buf - inbuf);
if (bytesRead < 0)
{
error_processing_here();
continue;
}
if (bytesRead == 0) // no data read to read
{
gettimeofday (&now, NULL);
if ((now.tv.sec - start.tv_sec) * 1000000 +
now.tv.usec - start.tv_usec > timeout_value_in_microsecs)
{
done = 2; // timeout
continue;
}
sleep(1); // not timed out yet, sleep a second
continue;
}
inbuf += bytesRead;
if (we have read all we want)
done = 1;
}
if (done == 2)
timeout_condition_handling();
close(fd);
return 0;
}
總結
以上是生活随笔為你收集整理的java串口监听超时_从串口读取时如何实现read()的超时(C / C)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 四川学生遇地震全班1秒钟避险 网友称平时
- 下一篇: 定向降准和降准有什么区别?定向降准对市场