How hard is it if we don't close the file in Perl?

How hard is it if we don't close the file in Perl? Will it affect the program or file if I get it again in the same program?

+4
source share
3 answers

Global file descriptors will remain until your program exits. This may be bad, but since you probably shouldn't use global file descriptors, this is not a problem.

The lexical file descriptors with my are equal to close d when their area remains / their number of links drops to zero.

If the file descriptor name is reused, the previous file descriptor close d is implicit. The following script uses the same file descriptor to print the first five lines of any number of files:

 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 } 

When working with files, explicitly closing FH does not matter. However, this is important when performing IPC. Closing the write tip in the tube indicates the EOF at the end of the read.

When fork ing, all unused file descriptors must be closed because they are duplicated during forking. This means that closing the pipe in one process may not send the desired EOF, because the same channel is still open in the corresponding process.

Here is a program that demonstrates the importance of close in 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"; } 

The result of this program is numbers from 1 to 5. Then the child element closes its end in the pipe, causing SIGPIPE in the parent element. While the parent is dying, the child is delayed for 5 seconds until he dies.

This works because the parent has closed the read end for the pipe. If close $out is removed from the parent, SIGPIPE will not triggerd, and the program prints the numbers ad infinitum.

+11
source

If you do not close the files, your program may end up with free file descriptors.

man perlfunc:

 close Closes the file or pipe associated with the filehandle, flushes the IO buffers, and closes the system file descriptor. 
+2
source

Some output errors may be delayed until the file is closed. Therefore, it is generally recommended that you close files and check the return value. As in

 # open (my $fd, ">", $fname) somewhere upstream close $fd or die "Couldn't finish writing to $fname: $!"; 

In addition, the program will successfully close global file descriptors on exit and lexical when they leave the area.

+1
source

Source: https://habr.com/ru/post/1437515/


All Articles