Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang bad file descriptor

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! \n")             break         }     } }() 
like image 990
Jared Mackey Avatar asked Nov 22 '15 04:11

Jared Mackey


2 Answers

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.

like image 188
HectorJ Avatar answered Sep 19 '22 02:09

HectorJ


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.

like image 38
jack wu Avatar answered Sep 19 '22 02:09

jack wu