当创建新文件是可以通过umask函数指定文件的访问权限。以下是文件权限值对应的数字:
/************************** * 函数功能:为进程设置文件模式创建屏蔽字,并返回以前的值; * 函数原型: * * mode_t umask (mode_t cmask); * 参数说明 * cmask是前面介绍的文件权限的9个值的若干个按位“或”构成,9个权限如下所示: **/ /***************************** * 文件访问权限 * st_mode屏蔽 意义 * S_IRUSR 用户-读 * S_IWUSR 用户-写 * S_IXUSR 用户-执行 ***************************** * S_IRGRP 组-读 * S_IWGRP 组-写 * S_IXGRP 组-执行 ***************************** * S_IROTH 其他-读 * S_IWOTH 其他-写 * S_IXOTH 其他-执行 ***************************** */
/* umask的主要作用是在创建文件时设置或者屏蔽文件的某些权限; * 下面举例子,在创建文件时指定文件的权限属性:mode &(~cmask); * 其中mode 是open或者creat函数的属性参数 */ #include "apue.h" #include <fcntl.h> #define RWRWRW (S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH) int main(void) { umask(0);//set the first umask //此时cmask值为000 if(creat("umask",RWRWRW) < 0)//creat参数的mode权限值为666 err_sys("creat error for umask."); //最后创建成功的文件umask权限属性为mode &(~cmask),即为666 umask(S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);//set the second umask //此时cmask权限值为066 if(creat("bar",RWRWRW) < 0)//creat参数mode权限值依然为666 err_sys("creat error for bar."); //成功创建的文件bar权限属性为mode &(~cmask),即为600 exit(0); }若成功创建了文件umask和bar,则通过ls-l查看这两个文件的权限属性如下:
-rw------- bar -rw-rw-rw- umask
这两个函数是改变文件的权限。
/************************ * 以下的操作必须保证进程的有效用户ID必须等于文件的所有者ID,或者进程必须具有超级用户权限; * 函数功能:改变现有文件的访问权限; * 函数原型: * * int chmod(const char *pathname, mode_t mode); * int fchmod(int filedes, mode_t mode); * 说明: * chomd 函数是在指定的文件pathname进行操作; * fchmod 函数是在已打开的文件进行操作; * 参数说明: * mode 为以下权限值: * *********************************** * S_ISUID 设置用户ID * S_ISGID 设置组ID * S_ISVTX 保存正文(粘住性) * ********************************* * S_IRWXU 用户读、写和执行 * S_IRUSR 用户-读 * S_IWUSR 用户-写 * S_IXUSR 用户-执行 *********************************** * S_IRWXG 组读、写和执行 * S_IRGRP 组-读 * S_IWGRP 组-写 * S_IXGRP 组-执行 *********************************** * S_IRWXO 其他读、写和执行 * S_IROTH 其他-读 * S_IWOTH 其他-写 * S_IXOTH 其他-执行 ***************************** */ //其中缩进的9个权限是前面介绍的文件权限下面利用前面创建的文件umask和bar进行权限改变:
#include "apue.h" int main(void) { struct stat buf; if(stat("umask",&buf) < 0) err_sys("stat error for umask."); if(chmod("umask",(buf.st_mode & ~S_IXGRP) | S_ISGID) < 0) err_sys("chmod error for umask."); if(chmod("bar",S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) < 0) err_sys("chmod error for umask."); exit(0); }
-rw-r--r-- bar -rw-rwSrw- umask
其中S是ls中组执行权限的表示,修改umask文件时,首先要用stat函数获取当前权限属性,然后再进行修改;bar文件是权限设置为绝对值权限,所以不管原来的权限如何都无关,则不需要stat函数获取当前权限。
更改文件用户ID和组ID
****************************************** * 函数功能:更改文件用户ID和组ID * 返回值:若成功返回0,若出错返回-1; * 函数原型: * int chown(const char *pathname, uid_t owner, gid_t group); * int fchown(int filedes, uid_t owner, gid_t group); * int lchown(const char *pathname, uid_t owner, gid_t group); * 若文件是符号链接时,lchown更改的是符号链接本身的所有者,而不是符号链接所指向的文件; * 其他操作相似; * 若参数owner或group的值为-1时,表示不更改对应的ID; */