linux下創建文件的文件權限問題


今天發現創建文件的權限和自己規定的權限不一致,了解到了權限掩碼的問題,這里總結一下。

首先權限掩碼umask是chmod配套的,總共為4位(gid/uid,屬主,組權,其它用戶的權限),不過通常我們都只用到后面3個,第一個是特殊的權限位,暫時沒有很了解。比如chmod 0777 file 就代表給file設置屬主、組內用戶、其他用戶分別是rwx、rwx、rwx的權限。

在我的ubuntu15.04下,umask默認是0002,可以用umask指令查看,加上參數-S會更加易懂:

掩碼,顧名思義,是用來掩蓋了一些bit,這些bit在這里就表示權限,比如從上面的圖我們可以看到0002就是掩蓋了其他用戶的w權限(o=rx),因為2在二進制是010,我們創建文件時候規定的文件權限***是要和掩碼的反碼按位相與的,這樣才可以屏蔽掉某個位。比如創建文件的時候指定了0666,那么0666 & ~0002 = 0664,最終建立的文件權限為 rw-rw-r--。

另外,linux下(不包含權限掩碼umask)規定了文件的默認權限是0666(去除了執行權限x可以減少非常多的攻擊,因為很多病毒文件如果創建出來沒有執行權限的話,就失去了意義),目錄的默認權限是0777。所以,我們如果新建一個文件,文件權限還要和權限掩碼umask按位相與,即0666 & ~0002 = 0664(我的電腦上),最后得到的0664(rw-rw-r--)才是文件的真正權限,同理,創建一個目錄(0777 & ~0002 = 0775,即rwxrwxr-x)也一樣:

 

我們可以用umask命令來改變權限掩碼的值,相應的,我們創建的文件也會要和umask按位相與,會少相對應的部分權限:

 

相應的,c也有個umask函數,我們用c也可以查看和改變umask的值,但是,修改的僅僅是調用umask()這個函數的進程的值,也就是其余的umask值不變,我們可以用shell命令umask查看一下,會發現umask還是原來的值,所以在c語言里面調用的umask只會改變調用進程的umask。查看man幫助手冊可以知道,fork出來的子進程也會繼承父進程的umask,也就是說父進程如果修改了權限掩碼為0001,那么fork得到的子進程將會和父進程保持一直的權限掩碼0001而不是系統的0002或者0022。

當我們用c語言的open(linux的系統函數)來創建一個新文件的時候(即第二個參數指定O_CREAT),我們一定要指明第三個參數的權限是什么,默認的權限並不是linux默認的0666,所以不指定的話我也不知道是什么(感覺每次創建的都不一樣?)。因此,保險起見,我們在用open創建一個文件的時候,就按照自己的需求(沒有的話就按照linux默認的0666)指定創建的文件權限,而制定了這個權限以后,還要和當前進程的權限掩碼按位相與,這樣才會得到最終的文件權限。
O_CREAT
    If the file exists, this flag has no effect except as noted under O_EXCL below. Otherwise, the file is created; the user ID of the file is set to the effective user ID of the process; the group ID of the file is set to  the group ID of the file's parent directory or to the effective group ID of the process;  and the access permission bits (see <sys/stat.h>) of the file mode are set to the value of the third argument taken as type mode_t modified as follows: a bitwise-AND is performed on the file-mode bits and the corresponding bits in the complement of the process' file mode creation mask. Thus, all bits in the file mode whose corresponding bit in the file mode creation mask is set are cleared. When bits other than the file permission bits are set, the effect is unspecified. The third argument does not affect whether the file is open for reading, writing or for both. 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM