Golang 错误的文件描述符

标签 go file-descriptor

在我的 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/

相关文章:

html - Golang 在 Revel 中将字符串渲染为 html

go - 为什么在使用 select 并顺序将值输入 2 个 channel 时所有 goroutine 都处于休眠状态?

sockets - 套接字和文件描述符

go - 如何将可变参数传递给其他函数

arrays - go程序比较两个数组并将匹配的元素存储在golang中的第三个数组中

go - 我不了解此处的评估规则

java - 在关闭文件进行读取之前打开文件进行写入是否不正确?

android - 无需 root 即可永久增加 Android 中的文件描述符 ulimit

c - EAGAIN 后强制阻塞读取?

c - Ubuntu Linux 使用 Unix 域套接字发送文件描述符