设置os.Mkdir权限 [英] Setting os.Mkdir permissions

查看:90
本文介绍了设置os.Mkdir权限的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用os.Mkdir创建具有特定权限的目录,但是由于某些原因,我无法使其正常工作.

I'm trying to create directories with certain permissions using os.Mkdir but I cannot make it work, for some reason.

我的测试程序是:

package main

import (
        "log"
        "os"
)

func main() {                 
    err := os.Mkdir("testdir", 0775)
    if err != nil {              
        log.Print(err)
    }
}

但是,创建的目录具有默认的0755权限:

However, the created directory has the default 0755 permissions:

drwxr-xr-x 2 user user 4096 Jan 10 10:14 testdir

shell中的chmod可以正常工作,所以我不确定Go程序为什么不起作用.

A chmod from the shell works just fine, so I'm not sure why the Go program is not working.

推荐答案

在创建文件时,类Unix系统使用权限掩码(umask)创建默认权限.

When creating a file, Unix-like system use a permission mask (umask) to create the default permissions.

具有 0022 umask 值,最多将创建具有 0755 权限的新目录.新文件最多具有 0644 的权限.

With a umask value of 0022, new directories will be created with permissions 0755 at most. New files will have permissions 0644 at most.

如果要创建具有权限 0775 的新目录,则必须将umask值设置为 0002 .

If you want to create a new directory with permissions 0775, then you have to set your umask value to 0002.

解决此问题的另一种方法是在创建文件后修改权限:使用 os.Mkdir 创建具有默认权限的文件,然后使用 os.Chmod 修改这些权限.代码>.

An other way of working this around is to modify the permissions after creating the file : Create it with default permissions with os.Mkdir, then modify those permissions with os.Chmod.

这篇关于设置os.Mkdir权限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆