如何在C++中无阻塞地从USB设备轮询数据?
非阻塞轮询USB串口设备的问题与解决
问题背景
我有一台通过USB连接的设备,每隔几秒会输出以换行符分隔的字符流。我需要实现重复轮询该设备获取输入,且无输入时不会阻塞。尝试使用poll()函数但无法正常运行,排查困难。设备路径为/dev/ttyACM0,执行cat /dev/ttyACM0命令可以正常看到数据流。
最初触发段错误的程序
#include <iostream> #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <poll.h> #include <unistd.h> int main (int argc, char* argv[]){ char buf[1024]; int fd = open("/dev/ttyACM0", O_RDONLY | O_NONBLOCK); int ret; if (fd < 0){ std::cout << "ERROR" << fd << std::endl; } int i; struct pollfd *pfds; while(1){ pfds->fd = 0; pfds->events = POLLIN; ret = poll(pfds, 1, 0); if (ret > 0) { if (pfds->revents & POLLWRBAND) { i = read(0, buf, 1024); if (!i){ printf("stdin closed\n"); return 0; } std::cout << i << std::endl; } } } return 0; }
修复后的可用版本
#include <poll.h> #include <iostream> #include <cstring> #include <fcntl.h> #include <unistd.h> int main(){ char readBuf[5]; char c; std::string buf; int counter = 0; int ret; int i; struct pollfd mypoll; int fd = open("/dev/ttyACM0", O_RDONLY | O_NONBLOCK); //init mypoll memset(&mypoll, 0, sizeof(mypoll)); mypoll.fd = fd; mypoll.events = POLLIN; while(1){ // poll (pointer to pollfd, number of polls, timeout) // noneg = successful poll // 0 = systemcall timeout (no data) // -1, errno set to indicate error ret = poll(&mypoll, 1, 0); if (ret == 1){ int bytes_read = read(fd, readBuf, sizeof(readBuf)); for (i = 0; readBuf[i] != '\n' && i < bytes_read; i++){ buf.push_back(readBuf[i]); } std::cout << "#" << buf << "#" << std::endl; buf = ""; } } printf("done\n"); close(fd); return 0; }
内容的提问来源于stack exchange,提问作者user19802847
相关产品推荐
相关产品推荐

