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
};