Go to ioutil.ReadFile ()

I run a program in Go that continuously sends data after reading the /proc/stat file. Using ioutil.ReadFile("/proc/stat") After starting about 14 hours, I got an error: too many files open /proc/stat Click here for the code snippet.

I doubt that defer f.Close ignored by Go sometimes or skips it.


Code snippet (in case play.golang.org dies earlier than stackoverflow.com):

 package main import ("fmt";"io/ioutil") func main() { for { fmt.Println("Hello, playground") fData,err := ioutil.ReadFile("/proc/stat") if err != nil { fmt.Println("Err is ",err) } fmt.Println("FileData",string(fData)) } } 
+4
source share
2 answers

Probably the reason is that somewhere in your program:

  • you forgot to close the files, or

  • you rely on the garbage collector to automatically close files when the object completes, but Go's conservative garbage collector does not. In this case, you should check the memory consumption of your program (regardless of whether it constantly increases when the program starts).

In any case, try checking the contents of /proc/PID/fd to see if the number of open files increases while the program is running.

+4
source

If you are sure that you are executing the f.Close () function, it still has a problem, perhaps it is due to the fact that your other connection, for example, connecting to MYSQL, will also cause a problem, especially in a loop, and you will forget to close compound.

Always do:

 db.connection.... **defer db.Close()** If it is in loop loop db.connection.... **defer db.Close()** end 

Do not put db.connection before the loop

0
source

Source: https://habr.com/ru/post/1395162/


All Articles