Linux下的umask函數

來源:互聯網
上載者:User

umask函數為進程設定檔案模式建立屏蔽字,並返回以前的值。函數原型為:

#include <sys/stat.h>

mode_t umask(mode_t cmask);

cmask是由下表列出的9個常量中的若干個按位“或”構成的

S_IRUSR       使用者讀

S_IWUSR      使用者寫

S_IXUSR       使用者執行

S_IRGRP       組讀

S_IWGRP      組寫

S_IXGRP       組執行

S_IROTH       其他讀

S_IWOTH      其他寫

S_IXOTH       其他執行

在Linux中一個檔案的許可權分為3組9個許可權  分別為上面列出的9個,組間的順序為使用者,組,其他。例如:

ls -l test

-rw-rw-rw- 1 shmily shmily 0  5月  6 17:16 test

表示test檔案的許可權為:使用者可讀可寫,組可讀可寫,其他可讀可寫 (r代表可讀 w代表可寫 x代表可執行 -代表未設定)

可用三位8進位數表示 則test的許可權為666

————————————————————————————————————————————————————————————————————————————

umask的主要作用是在建立檔案設定或者屏蔽掉檔案的一些許可權

在建立一個檔案時要指明該檔案的許可權,open函數的最後一個參數mode並不是要設定的許可權,它需要執行以下操作

mode & (~cmask)

例如《APUE》中的4_3的函數

#include "apue.h"#include <fcntl.h>  #define RWRWRW (S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH)  int main(void){     umask(0);     if (creat("foo", RWRWRW) < 0)        err_sys("create error for foo");     umask(S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);     if (creat("bar", RWRWRW) < 0)         err_sys("creat error for bar");     return 0;}        

在最初cmask為0,即 000 000 000

creat函數時設定mode為666

mode & (~cmask) = 110 110 110 & 111 111 111 = 110 110 110

所以foo檔案的許可權就是rw-rw-rw-

然後cmask為066,即000 110 110

crear函數的mode仍為666

mode & (~cmask) = 110 110 110 & 111 001 001 = 110 000 000

所以bar檔案的許可權為rw-------

shmily@pc-Shmily:~/code/UnixCode$ ls -l foo bar
-rw------- 1 shmily shmily 0  5月  6 17:16 bar
-rw-rw-rw- 1 shmily shmily 0  5月  6 17:16 foo

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.