chmod、fchmod
头文件
#include <sys/stat.h>
函数原型
int chmod(const char *path, mode_t mode);
int fchmod(int fd, mode_t mode);
int fchmod(int fd, mode_t mode);
功能
chmod函数在指定的文件上进行操作,改变现有文件的访问权限。fchmod对已打开的文件进行操作。
修改时,进程的有效用户ID必须等于文件的所有者ID,或是root运行的此进程。
参数
mode常量
S_ISUID (04000) set-user-ID (set process effective user ID on
execve(2))//执行时设置用户ID
S_ISGID (02000) set-group-ID (set process effective group ID on
execve(2); mandatory locking, as described in
fcntl(2); take a new file's group from parent direc-
tory, as described in chown(2) and mkdir(2))//执行时设置组ID
S_ISVTX (01000) sticky bit (restricted deletion flag, as described
in unlink(2))//保存正文(粘住位)
S_IRUSR (00400) read by owner//用户(所有者)读
S_IWUSR (00200) write by owner//用户(所有者)写
S_IXUSR (00100) execute/search by owner ("search" applies for direc-
tories, and means that entries within the directory
can be accessed)//用户(所有者)执行
S_IRGRP (00040) read by group//组读
S_IWGRP (00020) write by group//组写
S_IXGRP (00010) execute/search by group//组执行
S_IROTH (00004) read by others//其他读
S_IWOTH (00002) write by others//其他写
S_IXOTH (00001) execute/search by others//其他执行
S_IRWXU (UNIX) //用户读写执行
S_IRWXG (UNIX) //组读写执行
S_IRWXO (UNIX) //其他读写执行
unix环境高级编程的例子
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
int main(int argc, char * argv[])
{
struct stat statbuf;
if(stat("foo", &statbuf) < 0)
{
printf("stat error for foo\n");
}
if(chmod("foo", (statbuf.st_mode & ~S_IXGRP) | S_ISGID) < 0)
{
printf("chmod error for foo\n");
}
if(chmod("bar", S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) < 0)
{
printf("chmod error for bar\n");
}
exit(0);
}