(transfer) go new file permission does not match the setting

Time:2019-11-24

Original: https://blog.csdn.net/lipengfeihb/article/details/54415283

I. Problems

fileName := "/Users/my/tests/perm_file"
f, _ := os.OpenFile(fileName, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
// code
f.Close()

The above code is to open a file. If the file does not exist, a new file will be created. At the same time, the permissions are set to 0666 (- RW RW RW RW -), but the permissions of the actually generated file may not be the same as you think:

bogon:tests didi$ ll perm_file
-rw-r--r-- 1 my staff 0 1 12 16:06 perm_file

This is related to the umask value, which is described below

Function Description: Specifies the preset permission mask when creating the file.
Language method: umask [- S] [permission mask]
Supplementary note: umask can be used to set [permission mask]. [permission mask] is composed of three octal digits. After subtracting the existing access permission from the permission mask, the default permission can be generated when creating a file.
Parameter:
-S represents the permission mask as text.
File: use octal base 666, i.e. no x-bit (executable bit) RW – RW – RW -. The execution bit should be added by the user.

Umask is a security mechanism of the system. By setting different permissions, it can limit the user’s operation and effectively ensure the integrity of the file.

Let’s go on to the above example
The required permission is – R w-rw-rw -, but the actual generated file permission is – rw-r – R -, and the w permission of user group and other users is removed. View the umask value of the system

bogon:tests my$ umask

bogon:tests my$ umask
0022

Umask value is 0022, R is 4, W is 2, X is 1, which corresponds to the following

User group other users
Required – RW – RW – RW-
Subtract umask 0 2 (W) 2 (W)
Get – RW – R – R –
II. Solutions
1. Set umask value

syscall.Umask(0)

2. Reassign permissions through Chmod

os.Chmod(fileName, 0666)