Skip to main content

Command Palette

Search for a command to run...

一個 Group Write Permission 的坑

Linux Group Write Permission

Published
2 min read

Group Write Permission

Python open/Golang open 開新檔案時,並不是直接按照 user 給的權限。

例如:

package main

import (
    "os"
)

func main() {
    os.OpenFile("aa.lock", os.O_RDWR|os.O_CREATE, 0664)
}

沒特別設定是沒辦法生出權限為 0664 的檔案。

這主要是源於 os.OpenFile 使用的 linux open,而根據 man open:

The effective mode is modified by the process's umask in the usual way: in the absence of a default ACL, the mode of the created file is (mode & ~umask).

而 default umask 是 022 ,意思是預設把 group write / other write 關掉。

所以要解決的話有兩個方法:

當然還有土法煉鋼的方式:

  • 建立完檔案直接用 chmod 更動,但是這樣建立檔案/chmod會有時間差。

umask

在呼叫 open 前先設定 umask。 要注意這設定是 process 級別的,所以假如嘗試這樣處理

oldValue = umask(002)
// ...
umask(oldValue)

這段就不會是 thread-safe 。

當然,可以考慮讓整隻程式都 umask(002),但挺髒的。

Default folder ACL

設定該檔案的資料的預設 Auth Control List 算是一個比較健康的方法:

umasktest 是上面的 golang 程式

$ ../umasktest/umasktest 
$ ls -al
total 12
drwxrwxr-x 2 alice   myteam  4096 Feb 18 10:28 .
drwxr-xr-x 5 root    root    4096 Feb 18 10:26 ..
-rw-r--r-- 1 alice   myteam     2 Feb 18 10:26 1
-rw-r--r-- 1 alice   myteam     0 Feb 18 10:28 aa.lock 
# 設定前沒有 group write 權限
$ setfacl -d -m g:myteam:rwx .
$ getfacl .
# file: .
# owner: alice
# group: myteam
user::rwx
group::rwx
other::r-x
default:user::rwx
default:group::rwx
default:group:myteam:rwx
default:mask::rwx
default:other::r-x

$ rm aa.lock 
$ ../umasktest/umasktest 
$ ls -al
total 12
drwxrwxr-x+ 2 alice   myteam  4096 Feb 18 10:32 .
drwxr-xr-x  5 root    root    4096 Feb 18 10:26 ..
-rw-r--r--  1 alice   myteam     2 Feb 18 10:26 1
-rw-rw-r--+ 1 alice   myteam     0 Feb 18 10:32 aa.lock # 有了!

More from this blog

簡介 C++ 的 Type Erase (用多型和模板做 Duck Type)

起點 讓我們先從 template 出發:foo 需要一個 callback function。 template<typename Func> void foo(Func callback) { // ... callback(); } 但是這會讓編譯錯誤訊息有點模糊:假如 callback 並不是一個可以呼叫的函數指標,或者並不是一個 callable object ,那編譯器會說錯出在第四行。但是我們都希望,編譯器在呼叫函數時就幫我們指出:這不是 foo 想要的 call...

May 14, 20243 min read

帕秋莉的魔法筆記

45 posts

後端工程師。

不定時張貼一些寫扣時的筆記。