本篇博文內(nèi)容摘自《UNIX環(huán)境高級(jí)編程》(第二版),僅作個(gè)人學(xué)習(xí)記錄所用。關(guān)于本書可參考:http://www.apuebook.com/。
這兩個(gè)函數(shù)使我們可以更改現(xiàn)有文件的訪問權(quán)限:
#include <sys/stat.h>int chmod( const char *pathname, mode_t mode );int fchmod( int filedes, mode_t mode );兩個(gè)函數(shù)返回值:若成功則返回0,若出錯(cuò)則返回-1
chmod函數(shù)在指定的文件上進(jìn)行操作,而fchmod函數(shù)則對(duì)已打開的文件進(jìn)行操作。
為了改變一個(gè)文件的權(quán)限位,進(jìn)程的有效用戶ID必須等于文件的所有者ID,或者該進(jìn)程必須具有超級(jí)用戶權(quán)限。
參數(shù)mode是表4-8中所示常量的某種按位或運(yùn)算構(gòu)成的。
表4-8 chmod函數(shù)的mode常量,取自<sys/stat.h>
mode | 說明 |
S_ISUID S_ISGID S_ISVTX | 執(zhí)行時(shí)設(shè)置用戶ID 執(zhí)行時(shí)設(shè)置組ID 保存正文(粘住位) |
S_IRWXU S_IRUSR S_IWUSR S_IXUSR | 用戶(所有者)讀、寫和執(zhí)行 用戶(所有者)讀 用戶(所有者)寫 用戶(所有者)執(zhí)行 |
S_IRWXG S_IRGRP S_IWGRP S_IXGRP | 組讀、寫和執(zhí)行 組讀 組寫 組執(zhí)行 |
S_IRWXO S_IROTH S_IWOTH S_IXOTH | 其他讀、寫和執(zhí)行 其他讀 其他寫 其他執(zhí)行 |
程序清單4-4 chmod函數(shù)實(shí)例
[root@localhost apue]# cat PRog4-4.c#include "apue.h"int main(void){ struct stat statbuf; /* turn on set-group-ID and turn off group-execute */ if(stat("foo", &statbuf) < 0) err_sys("stat error for foo"); if(chmod("foo", (statbuf.st_mode & ~S_IXGRP) | S_ISGID) < 0) err_sys("chmod error for foo"); /* set absolute mode to "rw-r--r--" */ if(chmod("bar", S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) < 0) err_sys("chmod error for bar"); exit(0);}
新聞熱點(diǎn)
疑難解答
圖片精選