英文:
Go bug in ioutil.ReadFile()
问题
我正在使用Go语言编写一个程序,在读取文件/proc/stat
后连续发送数据。
使用ioutil.ReadFile("/proc/stat")
。
运行大约14小时后,我得到了错误:too many files open /proc/stat
。
点击这里查看代码片段。
我怀疑Go语言有时会忽略defer f.Close
,或者跳过它。
代码片段(以防play.golang.org比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))
}
}
英文:
I am running a program in Go which sends data continuously after reading a file /proc/stat
.
Using ioutil.ReadFile("/proc/stat")
After running for about 14 hrs i got err: too many files open /proc/stat
Click here for snippet of code.
I doubt that defer f.Close
is ignored by Go sometimes or it is skipping it.
The snippet of code (in case play.golang.org dies sooner 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))
}
}
答案1
得分: 5
可能的原因是在你的程序中的某个地方:
-
你忘记关闭文件,或者
-
你依赖垃圾回收器在对象最终化时自动关闭文件,但是Go的保守垃圾回收器无法做到这一点。在这种情况下,你应该检查程序的内存消耗(在程序运行时是否持续增加)。
无论哪种情况,尝试检查<code>/proc/PID/fd</code>的内容,看看在程序运行时打开的文件数量是否在增加。
英文:
The reason probably is that somewhere in your program:
-
you are forgetting to close files, or
-
you are leaning on the garbage collector to automatically close files on object finalization, but Go's conservative garbage collector fails to do so. In this case you should check your program's memory consumption (whether it is steadily increasing while the program is running).
In either case, try to check the contents of <code>/proc/PID/fd</code> to see whether the number of open files is increasing while the program is running.
答案2
得分: 0
如果你确定你已经执行了f.Close(),但仍然存在问题,可能是因为你的其他连接,例如与MYSQL的连接,也会导致问题,特别是在循环中,并且你忘记关闭连接。
始终执行以下操作:
db.connection....
**defer db.Close()**
如果在循环中
循环
db.connection....
**defer db.Close()**
结束
不要将db.connection放在循环之前。
英文:
If you are sure you Do the f.Close(),it still has the proble,Maybe it is because your other connection,for example the connection to MYSQL,also will be cause the problem,especially,in a loop,and you forget to close the connection.
Always do :
db.connection....
**defer db.Close()**
If it is in loop
loop
db.connection....
**defer db.Close()**
end
Do not put the db.connection before the loop
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论