I am simply reading the /proc/diskstats
file. My code is:
func ReadFromFile(filepath string)(string){
defer func() {
if err1 := recover(); err1 != nil {
fmt.Println("!!!!!!!!!!!!!!!!Panic Occured and Recovered in readFromFile(), Error Info: ", err1)
}
}()
strData := ""
data, err := ioutil.ReadFile(filepath)
if err != nil{
fmt.Println("File read error: ", err)
return ""
}
strData = string(data)
return strData
}
The error I am getting is:
File read error: open /proc/diskstats: too many open files
Not only for this file, I am also getting the same error for some other files.
I have also run this command:
root@golang:~# lsof|wc -l
785
Please guide me.
Basically in UNIX platforms, the OS places a limit to the number of open file descriptors that a process may have at any given time.
The error too many open files
is raised since you have reached the limit of file (and or pipe or socket)currently opened and you are trying to open a new file (and or pipe or socket).
To avoid this problem you must close the file when you have finished to use the open file using the Close()
function
I ran into the same problem (maybe different circumstances or setup) and fixed it differently. I created a simple and simplified example:
func some_func(file_name []string) {
for _, file_name := range file_names {
f, _ := os.Create(file_name)
// defer f.Close() // bad idea
_, _ = f.Write("some text")
f.Close() // better idea
}
}
It is a bad idea, because defer
will be executed, when some_func
will return, which could take a while - depending on the loop size.