提供一份测试demo:
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <fcntl.h> #include <sys/file.h> #include <sys/mman.h> #include <sys/stat.h> int open_file(char *path) { int fd; fd = open(path,O_RDONLY); if (-1 == fd){ printf("error open\n"); return -1; } return fd; } int get_file_size(int fd) { struct stat st; int ret; ret = fstat(fd,&st); if (-1 == ret){ printf("fstat failed\n"); return -1; } return st.st_size; } typedef struct gpios{ char value; }GPIOS; int get_value_mmap_files(int fd, int len, char *value) { GPIOS *gpio; gpio = mmap(NULL,len,PROT_READ,MAP_SHARED,fd,0); if (NULL == gpio || gpio == (void*) - 1){ printf("error mmap\n"); return -1; } *value = gpio->value; munmap(gpio,len); close(fd); return 0; } int main(int argc, char **argv) { //open file //get size of file //use mmap //close char path[32] = "/tmp/wat"; int fd; int len; int ret; char value; fd = open_file(path); if(-1 == fd) return -1; len = get_file_size(fd); if (-1 == len) return -1; ret = get_value_mmap_files(fd,len,&value); if (-1 == ret) return -1; printf("The gpio level is %c\n",value); return 0; }
其实就利用mmap代替read/fread读取文件内容,可以参考,了解应用。
mmap()系统调用使得进程之间通过映射同一个普通文件实现共享内存。普通文件被映射到进程地址空间后,进程可以像访问普通内存一样对文件进行访问,不必再调用read(),write()等操作