问题描述
在尝试附加到我的日常程序中的日志记录文件时,我收到了错误的文件描述符。
I am getting a bad file descriptor when trying to append to a logging file within my go routine.
写入./log.log:坏档案描述符
该文件存在并且具有666的权限。起初我想也许是因为他们每个人都试图同时打开文件。我实现了一个互斥体来试图避免这种情况,但得到了同样的问题,所以我删除了它。
The file exists and has 666 for permissions. At first I thought well maybe it is because each one of them is trying to open the file at the same time. I implemented a mutex to try and avoid that but got the same issue so I removed it.
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 { /*[...]*/ }
解释一下,这里是linux文档打开::
$ b
To explain, here is the linux documentation for open: http://man7.org/linux/man-pages/man2/openat.2.html :
如果您检查/usr/local/go/src/syscall/zerrors_linux_amd64.go:660,你可以看到:
If you check /usr/local/go/src/syscall/zerrors_linux_amd64.go:660, you can see that:
O_RDONLY = 0x0
O_RDWR = 0x2
O_WRONLY = 0x1
所以默认情况下,只有文件描述符。
So by default you get a read-only file descriptor.
这篇关于Golang坏文件描述符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!