Golang坏文件描述符 [英] Golang bad file descriptor

查看:379
本文介绍了Golang坏文件描述符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在尝试附加到我的日常程序中的日志记录文件时,我收到了错误的文件描述符。

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文档打开: http://man7.org/linux/man-pages/man2/openat .bhtml
$ b

To explain, here is the linux documentation for open: http://man7.org/linux/man-pages/man2/openat.2.html :


参数标志必须包含以下其中一种访问模式:
O_RDONLY,O_WRONLY ,或者O_RDWR。这些请求分别打开文件read-
,只写,或读/写。

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,你可以看到:

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坏文件描述符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆