[转]用户态文件系统
转自:
用户态文件系统框架fuse https://zhuanlan.zhihu.com/p/59354174
libfuse hello_world 分析 https://yq.aliyun.com/articles/425979
框架
如图1所示,其中fuse_user是开发的用户态的文件系统程序,该程序启动的时候会将自己开发的接口注册到fuse中,比如读写文件的接口,遍历目录的接口等等。
同时,通过该程序在系统某个路径挂载fuse文件系统,比如/tmp/file_on_fuse_fs。此时如果在该目录中有相关操作时,请求会经过VFS到fuse的内核模块(上图中的步骤1),fuse内核模块根据请求类型,调用用户态应用注册的函数(上图中步骤2),然后将处理结果通过VFS返回给系统调用(步骤3)。
示例
#define FUSE_USE_VERSION 31 表示API version
1 /* 2 * build* 3 *gcc -o fuse_user fuse_user_main.c -D_FILE_OFFSET_BITS=64 -lfuse3 4 * 5 * usage* 6 * mkdir fuse_mount 7 * sudo fuse ./fuse_user fuse_mount 8 * mount //show whether new filesystem mounted on fuse_mount dir 9 * ls -alh fuse_mount 10 * */ 11 12 13 #define FUSE_USE_VERSION 31 14 #include <stdio.h> 15 #include <fuse3/fuse.h> 16 #include <string.h> 17 18 /* 这里实现了一个遍历目录的功能,当用户在目录执行ls时,会回调到该函数,我们这里只是返回一个固定的文件Hello-world。 */ 19 static int test_readdir(const char *path, void *buf, fuse_fill_dir_t filler, 20 off_t offset, struct fuse_file_info *fi, 21 enum fuse_readdir_flags flags) 22 { 23 printf( "tfs_readdir path : %s ", path); 24 25 return filler(buf, "Hello-world", NULL, 0,0); 26 } 27 28 /* 显示文件属性 */ 29 static int test_getattr(const char *path, struct stat *stbuf, 30 struct fuse_file_info *fi) 31 { 32 printf("tfs_getattr path : %s ", path); 33 if(strcmp(path, "/") == 0) 34 stbuf->st_mode = 0755 | S_IFDIR; 35 else 36 stbuf->st_mode = 0644 | S_IFREG; 37 return 0; 38 } 39 40 /*这里是回调函数集合,这里实现的很简单*/ 41 static struct fuse_operations tfs_ops = { 42 .readdir = test_readdir, 43 .getattr = test_getattr, 44 }; 45 46 int main(int argc, char *argv[]) 47 { 48 int ret = 0; 49 ret = fuse_main(argc, argv, &tfs_ops, NULL); 50 return ret; 51 }