Linux中的select
系统调用是一种I/O多路复用技术,它允许单个进程/线程处理多个I/O操作。select
函数监视多个文件描述符,等待其中任意一个变为可读、可写或有异常条件待处理。
select
、poll
、epoll
(Linux特有)等。select
进行串口通信#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/select.h>
#include <errno.h>
int main() {
int fd;
char buffer[256];
fd_set readfs; // 文件描述符集合
struct timeval timeout;
// 打开串口设备
fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NDELAY);
if (fd == -1) {
perror("open_port: Unable to open /dev/ttyS0 - ");
return 1;
}
// 设置串口参数(省略具体设置代码)
while (1) {
FD_ZERO(&readfs); // 清空文件描述符集合
FD_SET(fd, &readfs); // 将串口设备添加到集合
timeout.tv_sec = 5; // 设置超时时间为5秒
timeout.tv_usec = 0;
int ret = select(fd + 1, &readfs, NULL, NULL, &timeout);
if (ret == -1) {
perror("select error");
break;
} else if (ret == 0) {
printf("select timeout\n");
continue;
}
if (FD_ISSET(fd, &readfs)) { // 判断串口是否有数据可读
int n = read(fd, buffer, sizeof(buffer));
if (n > 0) {
buffer[n] = '\0';
printf("Received data: %s\n", buffer);
}
}
}
close(fd);
return 0;
}
select
返回-1:errno
获取具体错误信息。select
的超时时间设置。通过合理使用select
系统调用,并结合适当的错误处理机制,可以有效地进行串口通信的多路复用处理。
腾讯云数据库TDSQL训练营
腾讯云数据库TDSQL(PostgreSQL版)训练营
2022OpenCloudOS社区开放日
云+社区沙龙online第6期[开源之道]
云原生正发声
腾讯云数据库TDSQL训练营
腾讯云数据库TDSQL训练营
腾讯云数据库TDSQL训练营
腾讯云数据库TDSQL训练营
腾讯云数据库TDSQL训练营
腾讯云数据库TDSQL训练营
领取专属 10元无门槛券
手把手带您无忧上云