如果不在Perl中关闭文件,它有多严重?
如果我在同一程序中再次访问它,会影响程序或文件吗?
最佳答案
全局文件句柄将一直存在,直到程序退出。这可能很糟糕,但是由于您可能不应该使用全局文件句柄,因此这不是问题。
当保留其作用域/它们的引用计数降至零时,带有my
的词法文件句柄为close
d。
如果文件句柄的名称被重用,则先前的文件句柄将隐式包含close
d。以下脚本重用相同的文件句柄以打印任意数量的文件的前五行:
my $fh;
foreach my $filename (@ARGV) {
open $fh, "<", $filename or die "Can't open $filename"; # $fh is re-used
print scalar <$fh> // next for 1 .. 5; # // is the defined-or
}
在处理文件时,显式关闭FH并不重要。但是,进行IPC时至关重要。将写入端关闭到管道会指示EOF到读取端。
进行
fork
编码时,应关闭所有未使用的文件句柄,因为它们在分支时会重复。这意味着在一个进程中关闭管道可能无法发送所需的EOF,因为同一管道在相关进程中仍处于打开状态。这是一个演示ipt_code在IPC中的重要性的程序:
pipe my $out, my $in or die $!;
if (fork()) { # PARENT
close $out; # close unused handle (important!)
select $in;
$| = 1; # set $in to autoflushed (important!)
$SIG{PIPE} = sub {die "Parent"}; # die, when the pipe is closed
print ++$i, "\n" and sleep 1 while 1; # print one number per second
} else { # CHILD
close $in; # close unused handle
print scalar <$out> for 1 .. 5; # read numbers 1 to 5 from the pipe
close $out; # close the pipe (and trigger SIGPIPE)
sleep 5; # wait, then exit
die "Child";
}
该程序的输出是数字1到5。然后,子级将其末端关闭到管道,从而触发父级中的
close
。 parent 去世时, child 会徘徊5秒钟,直到也死去。这是有效的,因为父级将其读取端封闭到管道上。如果从父级中删除了
SIGPIPE
,则不会触发close $out
,并且程序会无限期地打印编号。
关于perl - 如果不在Perl中关闭文件,它有多严重?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12702869/