Chinaunix首页 | 论坛 | 博客
  • 博客访问: 893712
  • 博文数量: 299
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 2493
  • 用 户 组: 普通用户
  • 注册时间: 2014-03-21 10:07
个人简介

Linux后台服务器编程。

文章分类

全部博文(299)

文章存档

2015年(2)

2014年(297)

分类: LINUX

2014-07-07 20:42:40

【代码】file.c
#include
#include
#include
#include
#include
int main(int argc,char* argv[]){
 struct stat file_stat;
 int fd;
 if(2 != argc)                       //1
 {
  printf("Usage: %s filename\n",argv[0]);
  return 1;
 }
 if(stat(argv[1],&file_stat) == -1)   //2
 {
  perror("Can't get the information of the file!");
  return 1;
 }
 if(S_ISREG(file_stat.st_mode))      //3
 {
  printf("This is a regular file judged by S_ISREG.\n");
 }
 if(file_stat.st_mode & S_IFREG)
 {
  printf("This is a regular file judged by S_IFREG.\n");
 }
 printf("Owner ID: %d, Group ID: %d.\n",file_stat.st_uid,file_stat.st_gid);
 printf("Permission[before modified]: %o\n.",file_stat.st_mode & 0x1ff); //4
 
 
 if(chmod(argv[1],S_IRUSR|S_IWUSR|S_IXUSR|S_IWGRP|S_IWOTH)<0)   //5
 {
  perror("Can't modify the permission of the file.\n");
  return 1;
 }
 else
 {
  if(stat(argv[1],&file_stat) == -1)
  {
   perror("Can't get the information of the file!");
   return 1;
  }
  else
  {
   printf("Permission[after modified]: %o\n.",file_stat.st_mode & 0x1ff);
  }
 }

 umask(S_IWGRP | S_IRGRP | S_IXGRP | S_IROTH | S_IWOTH |S_IXOTH);  //6
 fd = open("test2",O_CREAT | O_RDWR, 0777);
 if(fd<0)
 {
  perror("Fail to creat file.\n");
  return 1;
 }
 close(fd);
 if(stat("test2",&file_stat) == -1)
 {
  perror("Fail to get the information of file test2.\n");
  return 1;
 }
 printf("After modify umask value, permission is %o.\n",file_stat.st_mode & 0x1ff);
 return 0;
}
 
【说明】
(1)argc=2,表示指针数组argv[]内部参数个数为2个,第一个指针指向字符串为可执行文件名,第二个指针指向执行时命令行的第一个参数。本程序执行只需要带一个参数,即一个已创建的文件名称。
(2)stat函数是通过指向路径的指针获得相关文件信息,该指针即为argv[]第二个参数指针,并将该文件信息写入stat函数第二个参数结构体内部。
(3)宏S_ISREG和S_IFERG都是用来检查文件类型,是否为常规文件,实现等价。此外还有检查文件是否为字符设备、块设备、符号链接等。
(4)file_stat.st_mode & 0x1ff:0x1ff换算为8进制为777,通过按位与运算计算权限。linux下文件的权限表示可以用三个8进制数表示,分别为u(用户主)-g(同组用户)-o(其他用户),每个8进制数的三个位分别表示读-写-执行权限,1表示有,0表示没有;另外ls命令显示的也是权限的一种,比如rw-r--r--表示用户主具有读写权限,同组和其他用户具有读权限。也就是说rw-r--r--和644等价。
(5)创建的文件默认权限就是644,通过chmod可以修改权限,S_IRUSR|S_IWUSR|S_IXUSR|S_IWGRP|S_IWOTH表示用户组权限读写执行,group和other为写权限,这样权限值就变为722了。
(6)出于安全考虑,linux新创建的文件,所有类型用户都是没有写权限的。默认的掩码是022,也就是说新创建文件的默认权限是666-022=644,即ls显示的rw-r--r--。
umask(S_IWGRP | S_IRGRP | S_IXGRP | S_IROTH | S_IWOTH |S_IXOTH)以后umask=077,因此用777创建,以后的权限实际值为777-077=700.
 
【执行结果】

 gcc -o file file.c
 ./file testfile
This is a regular file judged by S_ISREG.
This is a regular file judged by S_IFREG.
Owner ID: 1000, Group ID: 1000.
Permission[before modified]: 644    
Permission[after modified]: 722    
After modify umask value, permission is 700.

阅读(1469) | 评论(0) | 转发(0) |
0

上一篇:Linux 网络栈剖析

下一篇:linux文件I/O操作

给主人留下些什么吧!~~