【问题标题】:Getting uid and gid of a file [duplicate]获取文件的uid和gid [重复]
【发布时间】:2019-10-01 07:06:40
【问题描述】:

在 linux 中,stat 结构包含文件的 UID 和 GID。

有没有办法使用 Go(lang) 获取文件的相同信息(UID 和 GID)?

【问题讨论】:

  • 看起来 go 的 os 包有一个不包含该信息的 Stat 函数,但它有一个 Chown 函数接受 uid 和 gid ......那里奇怪的决定。

标签: linux go stat


【解决方案1】:

我想出了一个合理的方法。

import (
    "syscall"
    "os"
)

info, _ := os.Stat("/path/to/the/file")

var UID int
var GID int
if stat, ok := info.Sys().(*syscall.Stat_t); ok {
    UID = int(stat.Uid)
    GID = int(stat.Gid)
} else {
    // we are not in linux, this won't work anyway in windows, 
    // but maybe you want to log warnings
    UID = os.Getuid()
    GID = os.Getgid()
}

【讨论】:

  • 是的,我认为这不仅仅是“一种合理的做法”。这是的方法。 github.com/golang/go/issues/14753
  • 或者您也可以直接调用syscall.Stat(),它会返回*syscall.Stat_t,但这并非在所有目标操作系统上都可用(例如在Window上)。
  • 我不会为非 Unix-y 平台创建“假”UID 和 GID。像 type fileOwner struct { UID, GID int; Valid bool } 这样的结构会更好:它只会在其余字段有意义的系统上使用 Valid == true
  • @kostix os.Getuid() 在 Windows 上应该返回 -1。 Valid == true 检查等于 UID >= 0,使 Valid 字段冗余。
猜你喜欢
  • 1970-01-01
  • 2017-08-12
  • 1970-01-01
  • 2016-06-17
  • 1970-01-01
  • 1970-01-01
  • 2022-11-07
  • 2018-01-05
  • 2010-11-03
相关资源
最近更新 更多