您的位置:首页 > 编程语言

uc高级编程之权限

2016-07-26 23:20 411 查看
/*

  这两个函数可以使我们更改现有文件的访问权限

  int chomd(const char* pathname,mode_t mode)

  int fchomd(int filedes,mode_t mode)

     两个函数若成功则返回0,若失败则返回-1.

  chomd函数在指定的文件上进行操作,而fchomd 对已打开的文件进行操作

  为了改变一个文件的权限位,进程的有效用户ID必须等于文件的所有者ID,或者说,该进程必须有超级用户的权限

 

                        chomd函数的mode常量,取自<sys/stat.h>

                        mode                    说明

                        S_ISUID                执行时设置用户ID

                        S_ISGID                执行时设置组ID

                        S_ISVTX                保存正文(粘住位)

                        S_IRWXU                用户(所有者)读,写和执行

                        S_IRGRP               组读

                        S_IWGRP                组写

                        S_IXGRP               组执行

                        S_IRWXO                其他读写和执行

                        S_IROTH               其他读

                        S_IWOTH               其他写

                        S_IXOTH               其他执行

                        

*/

#include "apue.h"

#include <errno.h>

#include <stdarg.h>

/* printf a message and return to Caller.

 * Caller specfies "errnoflag".

 */

static void err_doit(int errnoflag,int error,const char* fmt,va_list ap)

{

   char  buf[MAXLINE];

   vsnprintf(buf,MAXLINE,fmt,ap);

   if(errnoflag)

   snprintf(buf+strlen(buf),MAXLINE-strlen(buf),": %s",strerror(error));

   strcat(buf,"\n");

   fflush(stdout);

   fputs(buf,stderr);

   fflush(NULL);

}

/*

 *   fatla error related to a system call.

 *   print a message and terminate.

 */

void err_sys(const char* fmt,...)

{

  va_list    ap;

  va_start(ap,fmt);

  err_doit(1,errno,fmt,ap);

  va_end(ap);

  exit(1);

}

int main(void)

{

   struct stat          statbuf;

   /* turn on set-group-ID and turn off group-execute*/

   if(stat("fooooo",&statbuf) < 0)  // stat 函数返回与该命名文件有关的信息结构

     err_sys("stat error for foo");

   if(chmod("fooooo",(statbuf.st_mode & ~S_IXGRP) | S_ISGID) < 0)

     err_sys("chomd error for foo");

   /* set absolute mode to "rw-r--r--"*/

   if(chmod("bar1111",S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH) < 0)

     err_sys("chomd error for bar");

   exit(0);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: