Bug #3290
closedFile descriptors not closed when all IO objects are collected
Description
=begin
The following script should raise an exception (invalid descriptor) on line [2] since the file object that allocated it should have been collected on line [1]. The script actually writes "hello" to the file so it seems that Ruby is leaking file descriptors.
def foo
f = File.open("a.txt", "w+")
fd = f.to_i
f = nil
fd
end
fd = foo
10.times { GC.start } # [1]
g = IO.new(fd, "w+") # [2]
g.write('hello')
g.close
The behavior is same in 1.8.6.
=end
Updated by mame (Yusuke Endoh) almost 16 years ago
- Status changed from Open to Rejected
=begin
Hi,
2010/5/14 Tomas Matousek redmine@ruby-lang.org:
def foo
f = File.open("a.txt", "w+")
fd = f.to_i
f = nil
fd
endfd = foo
10.times { GC.start } ? ? ?# [1]
This is not a bug. The IO has been not collected yet.
MRI's GC is not exact. In other words, MRI does not guarantee
that an object is collected as soon as it becomes unreachable.
You can see the IO closed if you open many files:
def foo(f)
f = File.open("#{ f }.txt", "w+")
fd = f.to_i
f = nil
fd
end
fds = ("a".."z").map {|f| foo(f) }
GC.start
fds.each do |fd|
g = IO.new(fd, "w+") #=> Bad file descriptor (Errno::EBADF)
end
--
Yusuke Endoh mame@tsg.ne.jp
=end