linux下的select用于串口接收数据时,select函数无法返回的问题

写串口程序接收数据时使用了select(fd+1,&readfds,&writefds,&exceptfds,NULL);

在接收线程里使用了select函数,还有另外一个线程有close(fd);即关闭串口

在调试过程中发现close之后,select函数仍然没有返回

后来查询资料得知,在socket编程中这样使用select是没问题的(如果是非正常断开,如意外断电,拔网线等情况,select也是无法检测到的);

因为在关闭socket时,你会接收到一条消息,所以select能返回;

但是在串口中,关闭端口是没有消息通知的,所以select无法知道,所以一直死在那,不会返回。

解决:

不使用select的无限等待模式,用等待超时;

struct timeval tv;

tv.tv_sec=5;

tv.tv_usec=0;

select(fd+1,&readfds,&writefds,&exceptfds,&tv);

如果哪位朋友有更好的解决方法请告知,谢谢

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Linux 中,串口接收不定长度的数据是一个常见的问题。你可以使用以下方法来解决这个问题: 1. 使用阻塞模式读取串口数据:在阻塞模式下,读取串口数据,程序会一直等待直到接收到指定长度的数据或者超。你可以使用`read()`函数来读取串口数据,并设置合适的超间。例如: ```c #include <fcntl.h> #include <termios.h> #include <unistd.h> int main() { int fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY); // 设置串口参数 struct termios options; tcgetattr(fd, &options); // 根据需求设置波特率、数据位、停止位等参数 cfsetispeed(&options, B9600); cfsetospeed(&options, B9600); tcsetattr(fd, TCSANOW, &options); char buffer[255]; int bytesRead = read(fd, buffer, sizeof(buffer)); if (bytesRead > 0) { // 处理接收到的数据 // ... } close(fd); return 0; } ``` 2. 使用非阻塞模式读取串口数据:在非阻塞模式下,读取串口数据,程序会立即返回,不管是否有数据可读。你可以使用`select()`函数来检查串口是否有可读数据,并使用`read()`函数来读取数据。例如: ```c #include <fcntl.h> #include <termios.h> #include <unistd.h> #include <sys/select.h> int main() { int fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NONBLOCK); // 设置串口参数 struct termios options; tcgetattr(fd, &options); // 根据需求设置波特率、数据位、停止位等参数 cfsetispeed(&options, B9600); cfsetospeed(&options, B9600); tcsetattr(fd, TCSANOW, &options); fd_set readfds; FD_ZERO(&readfds); FD_SET(fd, &readfds); struct timeval timeout; timeout.tv_sec = 1; // 设置超间为1秒 timeout.tv_usec = 0; char buffer[255]; int ready = select(fd + 1, &readfds, NULL, NULL, &timeout); if (ready > 0 && FD_ISSET(fd, &readfds)) { int bytesRead = read(fd, buffer, sizeof(buffer)); if (bytesRead > 0) { // 处理接收到的数据 // ... } } close(fd); return 0; } ``` 这些示例代码假设你的串口设备文件是`/dev/ttyS0`,你需要根据实际情况进行更改。另外,记得在编译链接`-lrt`库以使用`select()`函数。 请注意,以上代码只是演示如何读取串口数据,你还需要根据实际需求来处理接收到的数据
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值