os.MkdirAll()在创建嵌套目录时失败。

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

os.MkdirAll() fails when creating nested directories

问题

我有一个output/目录。当要创建的目录是

prefix := "output/2021-11-12.19.51.50.047614/2011-12"

os.MkdirAll(prefix, 0644) 失败了。但当目录是

prefix := "output/2021-11-12.19.51.50.047614"

时,它可以工作。

为什么 os.MkdirAll() 不能创建嵌套目录?这是它的目的。这是一个 bug 吗?

英文:

I have an output/ directory. When the directory to be created is

prefix := "output/2021-11-12.19.51.50.047614/2011-12"

os.MkdirAll(prefix, 0644) fails. When it is

prefix := "output/2021-11-12.19.51.50.047614"

it works.

Why can't os.MkdirAll() create nested directories? That's its purpose. Is this a bug?

答案1

得分: 1

os.MkdirAll函数的mode参数必须包含一些可执行 (111) 的位。

通常情况下,os.MkdirAll函数的mode参数应该是0777,至少在类Unix系统上是这样。在某些情况下,它应该是0700。(出于同样的原因,新创建的文件应该使用0666,而不是0644;有时适用0600。)

Go运行时将mode传递给操作系统级别的调用。在类Unix系统上,权限实际上是有意义的<sup>1</sup>,您提供的位会被当前umask设置中清除的任何已设置位修改。这个umask应该取消组和其他写权限,从而得到最终的0755权限,除非用户想要取消更多权限(例如07500700)或更少权限(例如0775)。

请记住,三组三位表示读取(r)、写入(w)和执行(x)权限:7rwx6rw-5r-x,依此类推。因此,0777表示rwxrwxrwx

类Unix系统要求在目录中命名文件时具有执行权限,因此如果您没有给自己执行权限,您将无法再使用该目录。


<sup>1</sup>在具有ACL的系统上,用户权限是有意义的,而“其他”可能是默认值,但“组”是不明确的。提供ACL的系统通常比简单的rwx控制具有更细粒度的控制。

英文:

The mode argument to os.MkdirAll must include some executable (111) bits.

In general, the mode argument to os.MkdirAll should be 0777, at least on Unix-like systems. In some cases, it should be 0700. (For the same reason, newly created files should be made with 0666, not 0644; sometimes 0600 is appropriate.)

The Go runtime passes the mode down to the OS-level calls. On Unix-like systems, where the permissions actually make sense,<sup>1</sup> the bits that you provide are then modified by clearing any bits set in the current umask setting. It's this umask that should take away group and other write permissions, resulting in the eventual 0755 permissions—unless, that is, the user wants to take away more permissions (resulting in, say, 0750 or 0700) or fewer (resulting in, say, 0775).

Remember that the three groups of three bits represent read (r), write (w), and execute (x) permissions: 7 is rwx, 6 is rw-, 5 is r-x, and so on. So 0777 represents rwxrwxrwx.

Unix-like systems require execute permission to name a file within a directory, so if you don't give yourself execute permission, you can no longer work with the directory.


<sup>1</sup>On systems with ACLs, user permissions make some sense and "other" might be reasonable as the default, but "group" is ill-defined. Systems that do offer ACLs usually have a lot finer granularity than the simple rwx controls anyway, though.

huangapple
  • 本文由 发表于 2021年11月13日 11:00:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/69951117.html
匿名

发表评论

匿名网友

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

确定