dregduc63699 2015-11-22 04:46
浏览 81
已采纳

Golang错误的文件描述符

I am getting a bad file descriptor when trying to append to a logging file within my go routine.

write ./log.log: bad file descriptor

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! 
")
            break
        }
    }
}()
  • 写回答

2条回答 默认 最新

  • duansan9435 2015-11-22 05:56
    关注

    You need to add the O_WRONLY flag :

    if f, err := os.OpenFile("./log.log", os.O_APPEND|os.O_WRONLY, os.ModeAppend); err != nil { /*[...]*/ }
    

    To explain, here is the linux documentation for open: 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.

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度