在我的 go 例程中尝试附加到日志文件时,我得到了一个错误的文件描述符。
写./log.log: 错误的文件描述符
该文件存在且具有 666 的权限。起初我想可能是因为他们每个人都试图同时打开文件。我实现了一个互斥锁来尝试避免这种情况,但遇到了同样的问题,所以我删除了它。
logCh := make(chan string, 150)
go func() {
for {
msg, ok := <-logCh
if ok {
if f, err := os.OpenFile("./log.log", os.O_APPEND, os.ModeAppend); err != nil {
panic(err)
} else {
logTime := time.Now().Format(time.RFC3339)
if _, err := f.WriteString(logTime + " - " + msg); err != nil {
fmt.Print(err)
}
f.Close()
}
} else {
fmt.Print("Channel closed! \n")
break
}
}
}()
最佳答案
您需要添加 O_WRONLY
标志:
if f, err := os.OpenFile("./log.log", os.O_APPEND|os.O_WRONLY, os.ModeAppend); err != nil { /*[...]*/ }
为了解释,这里是 open
的 linux 文档:http://man7.org/linux/man-pages/man2/openat.2.html :
The argument flags must include one of the following access modes: O_RDONLY, O_WRONLY, or O_RDWR. These request opening the file read- only, write-only, or read/write, respectively.
如果您检查 /usr/local/go/src/syscall/zerrors_linux_amd64.go:660 ,你可以看到:
O_RDONLY = 0x0
O_RDWR = 0x2
O_WRONLY = 0x1
所以默认情况下你会得到一个只读的文件描述符。
关于Golang 错误的文件描述符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33851692/