如何创建具有特定权限的目录

huangapple go评论85阅读模式
英文:

How to create a directory that has specific permissions

问题

我正在尝试使用Go语言创建一个具有特定权限的目录。
我需要 drwxrwxr-x 权限,但我不知道如何在 os.Mkdir() 中实现。
我尝试过 os.ModeDir、os.ModePerm 和 os.ModeSticky。

我在Linux上工作,不在乎解决方案是否适用于Windows。它可以适用,但不一定要求。

我的问题是,我正在尝试创建一个在程序内部后续使用的目录(程序创建目录,并将文件写入其中)。

英文:

I'm trying to create a directory in Go with very specific permissions.
I need drwxrwxr-x but I don't know how to do it with os.Mkdir().
I've tried os.ModeDir, os.ModePerm and os.ModeSticky

I'm on linux and I do not care if the solution will work in windows. it can, but it doesn't have to.

My issue is that I'm trying to create a directory that is later used within the program itself (the program creates the directory and it uses it to write files to).

答案1

得分: 1

引用自 https://stackoverflow.com/a/59963154/1079543 的内容:

> 所有程序都在一个umask设置下运行...这是系统将自动从文件和目录创建请求中删除的权限集合。

在启动程序时将umask设置为0会产生您所期望的结果:

//go:build unix
package main

import (
	"log"
	"os"

	"golang.org/x/sys/unix"
)

func main() {
	unix.Umask(0)
	if err := os.Mkdir("dirname", 0775); err != nil {
		log.Fatalf("failed to create directory: %v", err)
	}
}

根据 https://pkg.go.dev/cmd/go#hdr-Build_constraints//go:build unix 应为真,"如果GOOS是Unix或类Unix系统"。

以前的做法是使用 syscall.Umask(0)。根据 https://go.googlesource.com/proposal/+/refs/heads/master/design/freeze-syscall.md ,该包现在已被弃用。

英文:

To quote https://stackoverflow.com/a/59963154/1079543:

> all programs run with a umask setting...the set of permissions that the system will automatically remove from file and directory creation requests.

Setting the umask to 0 when you start the program produces the result you're looking for:

//go:build unix
package main

import (
	"log"
	"os"

	"golang.org/x/sys/unix"
)

func main() {
	unix.Umask(0)
	if err := os.Mkdir("dirname", 0775); err != nil {
		log.Fatalf("failed to create directory: %v", err)
	}
}

//go:build unix should be true "if GOOS is a Unix or Unix-like system" per: https://pkg.go.dev/cmd/go#hdr-Build_constraints

The old way to do this was with syscall.Umask(0). This package is now deprecated per: https://go.googlesource.com/proposal/+/refs/heads/master/design/freeze-syscall.md

huangapple
  • 本文由 发表于 2022年9月6日 02:16:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/73613328.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定