Linux下设备也被当作文件进行访问,Linux用户空间访问设备主要有3种方式。
1.查询方式
2.poll方式
3.select方式
1.查询方式
查询方式为最简单的方式,也是效率最低的方式。
函数原型:
int open(const char *pathname, int flags);
flats:O_RDONLY, O_WRONLY, O_RDWR
ssize_t read(int fd, void *buf, size_t count);
读成功返回读的字节数。
ssize_t write(int fd, const void *buf, size_t count);
写成功返回写的字节数。
#include <assert.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int main(int argc, char **argv)
{
char capacity[16] = {0};
int fd, ret;
fd = open("/sys/class/power_supply/max1720x_battery/capacity", O_RDONLY);
if (fd == -1) {
perror("open");
exit(EXIT_FAILURE);
}
while (1) {
read(fd, &capacity, sizeof(capacity));
printf("capacity = %s\n", capacity);
sleep(1);
}
close(fd);
return EXIT_SUCCESS;
}
2.poll方式
poll方式查询是否可对设备进行无阻塞的访问,如果不可访问,则会睡眠在等待队列上。
数据结构:
struct pollfd {
int fd; /* file descriptor */
short events; /* requested events */
short revents; /* returned events */
};
常用events:POLLIN,POLLOUT,POLLRDNORM,POLLWRNORM
注意:POLLIN和POLLRDNORM配合使用,POLLOUT和POLLWRNORM配合使用
函数原型:
int poll(struct pollfd *fds, nfds_t nfds, int timeout);
#include <assert.h>
#include <fcntl.h>
#include <poll.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int main(int argc, char **argv)
{
char capacity[16] = {0};
int fd, ret;
struct pollfd pfd;
fd = open("/sys/class/power_supply/max1720x_battery/capacity", O_RDONLY);
if (fd == -1) {
perror("open");
exit(EXIT_FAILURE);
}
pfd.fd = fd;
pfd.events = (POLLIN | POLLRDNORM);
while (1) {
puts("Starting poll...");
ret = poll(&pfd, (unsigned long)1, 5000); //wait for 5 secs
if (ret < 0) {
perror("poll");
}
if ((pfd.revents & POLLIN) == POLLIN) {
read(pfd.fd, &capacity, sizeof(capacity));
printf("POLLIN : capacity = %s\n", capacity);
}
}
close(fd);
return EXIT_SUCCESS;
}
3.select方式
select方式查询是否可对设备进行无阻塞的访问,如果不可访问,则会睡眠在等待队列上。
函数原型:
int select(int nfds, fd_set *readfds, fd_set *writefds,fd_set *exceptfds, struct timeval *timeout);
void FD_CLR(int fd, fd_set *set);
int FD_ISSET(int fd, fd_set *set);
void FD_SET(int fd, fd_set *set);
void FD_ZERO(fd_set *set);
#include <assert.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/select.h>
int main(int argc, char **argv)
{
char capacity[16] = {0};
int fd, ret;
fd_set fds;
fd = open("/sys/class/power_supply/max1720x_battery/capacity", O_RDONLY);
if (fd == -1) {
perror("open");
exit(EXIT_FAILURE);
}
while (1) {
puts("Starting select...");
FD_ZERO(&fds);
FD_SET(fd, &fds);
ret = select(1, &fds, NULL, NULL, NULL);
if (ret < 0) {
perror("select");
}
if (FD_ISSET(fd, &fds)) {
read(fd, &capacity, sizeof(capacity));
printf("SELECT : capacity = %s\n", capacity);
}
}
close(fd);
return EXIT_SUCCESS;
}