chmod,fchmod,and fchmodat Functions

来源:互联网 发布:java自学源代码 编辑:程序博客网 时间:2024/06/06 00:37

chmod, fchmod, fchmodat - change permissions of a file

原型如下:

#include <sys/stat.h>int chmod(const char *pathname, mode_t mode);int fchmod(int fd, mode_t mode);#include <fcntl.h>           /* Definition of AT_* constants */#include <sys/stat.h>int fchmodat(int dirfd, const char *pathname, mode_t mode, int flags);//Return: 0 if OK, -1 on error

chmod操作指定文件
fchmod操作已经打开的文件
fchmodat当路径为绝对路径或者fd参数为AT_FDCWD且路径为相对路径,这时候类似于chmod。此外,路径是相对于fd打开的目录。flag参数用于改变fchmodat的行为,当flag为AT_SYMLINK_NOFOLLOW被设置,fchmodat不跟随symbolic links

为了改变文件的权限位(permission bits),进程的effective user ID必须等于文件owner ID,或者进程拥有superuser permissions

mode用于位与(bitwise OR)常量如下:
figure 4.11
相对于9个文件权限常量增加了:
two set-ID 常量(S_ISUID, S_ISGID)
saved-text 常量(S_ISVTX)—不是POSIX.1的一部分,是单一UNIX规范的XSI选项。下一节讲解。
three combined 常量(S_IRWXU, S_IRWXG, S_IRWXO)

#include <sys/types.h>#include <sys/stat.h>#include <unistd.h>#include <stdio.h>#include <stdlib.h>#include <string.h>#include <errno.h>int main(){    struct stat stat_buf;/*获取文件的信息*/    if(stat("rwrwrw", &stat_buf) < 0)    {        fprintf(stderr, "stat error : %s \n", strerror(errno));        exit(-1);    }/*关闭文件的group write权限,打开set-group-ID*/    if(chmod("rwrwrw", stat_buf.st_mode & ~S_IWGRP | S_ISGID) < 0)    {        fprintf(stderr, "chmod error : %s \n", strerror(errno));        exit(-1);    }/*将文件的权限改成 user 可读可写可执行*/    if(chmod("nogrp", S_IRWXU) < 0)    {        fprintf(stderr, "chmod error : %s \n", strerror(errno));        exit(-1);    }    return 0;}

从执行前后的结果来看,文件权限正确修改。
Finally, note that the time and date listed by the ls command did not change after
we ran the program. We’ll see in Section 4.19 that the chmod function updates only the time that the i-node was last changed.

The chmod functions automatically clear two of the permission bits under the following conditions:

The group ID of a newly created file might potentially be a group that the calling process does not belong to. Recall from Section 4.6 that it’s possible for the group ID of the new file to be the group ID of the parent directory. Specifically, if the group ID of the new file does not equal either the effective group ID of the process or one of the process’s supplementary group IDs and if the process does not have superuser privileges, then the set-group-ID bit is automatically turned off. This prevents a user from creating a set-group-ID file owned by a group that the user doesn’t belong to.

Linux 3.2.0, Mac OS X 10.6.8, and Solaris 10 add another security feature to try to prevent misuse of some of the protection bits. If a process that does not have superuser privileges writes to a file, the set-user-ID and set-group-ID bits are automatically turned off. If malicious users find a set-group-ID or a set-user-ID file they can write to, even though they can modify the file, they lose the special privileges of the file.

0 0
原创粉丝点击