【TLPI读书笔记】 十六、扩展属性
概述
EA可用于实现访问列表和文件能力。EA 需要有底层文件系统的支持。
EA 命名空间
EA 的命名格式为 namespace.name。其中 namespace 用来把 EA 从功能上划分为截然不同的几大类,而 name 则用来在既定命名空间内唯一标识某个 EA。
可供 namespace 使用的值有4个:
- user
- trusted
- system
- security
通过shell 创建并查看 EA
在shell中,可执行 setfattr(1)
和getfattr(1)
命令来设置和查看文件的 EA。
扩展属性的实现细节
对 user 扩展属性的限制
user EA 只能施之以文件或目录
EA 在实现方面的限制
Linux VFS 针对所有文件系统上的 EA 均施以如下限制:
- EA 名称的长度不能超过 255 个字符
- EA 值的容量为 64KB
此外,某些文件系统对可与文件挂钩的 EA 数量及其大小还有更严格的限制,此处就不再赘述。
操控扩展属性的系统调用
创建和修改 EA
系统调用setxattr()
、lsetxattr()
以及fsetxattr()
用来设置文件的 EA 值之一
#include <sys/xattr.h>
int setxattr(const char *pathname, const char *name, const void *value, size_t size, int flags);
int lsetxattr(const char *pathname, const char *name, const void *value, size_t size, int flags);
int fsetxattr(int fd, const char *name, const void *value, size_t size, int flags);
All return 0 on success, or -1 on error
参数
pathname
/fd
:指定文件name
:定义 EA 的名称value
:指明缓冲区的指针size
:指明缓冲区大小flags
:可为该参数指定标志将这一行为控制得更为精准
返回值
- 成功:返回
0
- 失败:返回
-1
获取 EA 值
可利用系统调用getxattr()
、lgetxattr()
以及fgetxattr()
来获取 EA 值
#include <sys/xattr.h>
int getxattr(const char *pathname, const char *name, const void *value, size_t size);
int lgetxattr(const char *pathname, const char *name, const void *value, size_t size);
int fgetxattr(int fd, const char *name, const void *value, size_t size);
All return (nonnegative)size of EA value on success, or -1 on error
参数
pathname
/fd
:指定文件name
:定义 EA 的名称value
:指明缓冲区的指针size
:指明缓冲区大小
返回值
- 成功:返回 EA 值
- 失败:返回
-1
删除 EA 值
系统调用removexattr()
、lremovexattr()
以及fremovexattr()
用来删除文件的 EA
#include <sys/xattr.h>
int removexattr(const char *pathname, const char *name);
int lremovexattr(const char *pathname, const char *name);
int fremovexattr(int fd, const char *name);
All return 0 on success, or -1 on error
参数
pathname
/fd
:指定文件name
:定义 EA 的名称
返回值
- 成功:返回
0
- 失败:返回
-1
获取与文件相关联的所有 EA 的名称
执行系统调用listxattr()
、llistxattr()
以及flistxattr()
,所返回的列表会包含与某文件相关联的所有 EA 的名称
#include <sys/xattr.h>
int listxattr(const char *pathname, char *list, size_t size);
int llistxattr(const char *pathname, char *list, size_t size);
int flistxattr(int fd, char *list, size_t size);
All return number of bytes copied into list on success, or -1 on error
参数
pathname
/fd
:指定文件list
:定义获取结果的缓冲区地址size
:定义缓冲区大小
返回值
- 成功:返回拷贝到指定参数list中数据的字节数
- 失败:返回
-1
总结
本章所讲文件的扩展属性,即 EA,Linux 2.6 以来开始支持 EA,允许以 名称-值 对的形式将任意元数据与文件关联起来。