Skip to content

Instantly share code, notes, and snippets.

@lizmat
Created September 6, 2017 21:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lizmat/001726b47eb5051b247ef1498f3fda7d to your computer and use it in GitHub Desktop.
Save lizmat/001726b47eb5051b247ef1498f3fda7d to your computer and use it in GitHub Desktop.
closing files on exit
diff --git a/src/core/IO/Handle.pm b/src/core/IO/Handle.pm
index d76c820..811c0bd 100644
--- a/src/core/IO/Handle.pm
+++ b/src/core/IO/Handle.pm
@@ -19,6 +19,24 @@ my class IO::Handle {
$!encoding = $encoding || 'utf8')
}
+ # Make sure we close any open files on exit
+ my $opened := nqp::list;
+ END {
+ my int $i = 2;
+ my int $elems = nqp::elems($opened);
+ say "checking 3 .. { $elems - 1}";
+ nqp::while(
+ nqp::islt_i(($i = nqp::add_i($i,1)),$elems),
+ nqp::unless(
+ nqp::isnull(my $PIO := nqp::atpos($opened,$i)),
+nqp::stmts(
+ nqp::say("closing $i"),
+ nqp::closefh($PIO)
+)
+ )
+ )
+ }
+
method open(IO::Handle:D:
:$r, :$w, :$x, :$a, :$update,
:$rw, :$rx, :$ra,
@@ -165,6 +183,7 @@ my class IO::Handle {
)
),
);
+ nqp::bindpos($opened,nqp::filenofh($!PIO),$!PIO);
}
$!chomp = $chomp;
@@ -205,8 +224,9 @@ my class IO::Handle {
nqp::if(
nqp::defined($!PIO),
nqp::stmts(
+ (my int $fileno = nqp::filenofh($!PIO)),
nqp::closefh($!PIO), # TODO: catch errors
- $!PIO := nqp::null
+ nqp::bindpos($opened,$fileno,$!PIO := nqp::null)
)
)
}
@@ -746,10 +766,11 @@ my class IO::Handle {
# are our $*IN, $*OUT, and $*ERR, and we don't want them closed
# implicitly via DESTROY, since you can't get them back again.
nqp::if(
- nqp::defined($!PIO) && nqp::isgt_i(nqp::filenofh($!PIO), 2),
+ nqp::defined($!PIO)
+ && nqp::isgt_i((my int $fileno = nqp::filenofh($!PIO)), 2),
nqp::stmts(
nqp::closefh($!PIO), # don't bother checking for errors
- $!PIO := nqp::null
+ nqp::bindpos($opened,$fileno,$!PIO := nqp::null)
)
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment