Golang bad file descriptor

强颜欢笑 提交于 2019-12-03 10:12:11

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.

it used for me

the code before:

os.OpenFile(fileName, os.O_CREATE|os.O_APPEND, os.ModePerm)

and it occured the error: bad file descriptor,

then i add the os.O_WRONLY into the function

the code after:

os.OpenFile(fileName, os.O_CREATE|os.O_WRONLY|os.O_APPEND, os.ModePerm)

and it did't occured the problem.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!