1. 环境搭建
安装以下库:
sudo apt install libfuse-dev
sudo apt-get install fuse3
2.编译测试验证
在libfuse的代码下有关于fuse的实现demo,以高level的api hello为例子:
//系统回调函数
static struct fuse_operations hello_oper = {
.init = hello_init,
.getattr = hello_getattr,
.readdir = hello_readdir,
.open = hello_open,
.read = hello_read,
};
// fuse的入口
return fuse_main(args.argc, args.argv, &hello_oper, NULL);
编译:
gcc -Wall hello.c `pkg-config fuse3 --cflags --libs` -o hello
运行:
./hello /home/test/hello
通过 ls
命令查看 /home/test/hello下的文件, 可以看到有个hello的文件, cat
查看该文内容:
$ ls /home/test/hello/
hello
$ cat /home/test/hello/hello
Hello World!
代码的实现原理如下: 使用ls查看会回调到fuse的hello_readdir
函数中,filler
函数添加显示的内容,而 使用cat
命令则回调到hello_read
函数中.
static int hello_readdir(const char *path, void *buf, fuse_fill_dir_t filler,
off_t offset, struct fuse_file_info *fi,
enum fuse_readdir_flags flags)
{
....
filler(buf, ".", NULL, 0, 0);
filler(buf, "..", NULL, 0, 0);
filler(buf, options.filename, NULL, 0, 0);
return 0;
}
static int hello_read(const char *path, char *buf, size_t size, off_t offset,
struct fuse_file_info *fi)
{
....
len = strlen(options.contents);
if (offset < len) {
if (offset + size > len)
size = len - offset;
memcpy(buf, options.contents + offset, size);
} else
size = 0;
return size;
}
测试其他命令例如mkdir
, 此时命令行报错,说明未实现mkdir
相关的函数操作.
cd /home/test/hello && mkdir test
mkdir: 无法创建目录 “test”: 函数未实现
在passthrough.c
中实现的回调比较全,可以参考进行进行扩展:
static struct fuse_operations xmp_oper = {
.init = xmp_init,
.getattr = xmp_getattr,
.access = xmp_access,
.readlink = xmp_readlink,
.readdir = xmp_readdir,
.mknod = xmp_mknod,
.mkdir = xmp_mkdir,
.symlink = xmp_symlink,
.unlink = xmp_unlink,
.rmdir = xmp_rmdir,
.rename = xmp_rename,
.link = xmp_link,
.chmod = xmp_chmod,
.chown = xmp_chown,
.truncate = xmp_truncate,
#ifdef HAVE_UTIMENSAT
.utimens = xmp_utimens,
#endif
.open = xmp_open,
.read = xmp_read,
.write = xmp_write,
.statfs = xmp_statfs,
.release = xmp_release,
.fsync = xmp_fsync,
#ifdef HAVE_POSIX_FALLOCATE
.fallocate = xmp_fallocate,
#endif
#ifdef HAVE_SETXATTR
.setxattr = xmp_setxattr,
.getxattr = xmp_getxattr,
.listxattr = xmp_listxattr,
.removexattr = xmp_removexattr,
#endif
};