Greetings fellow monks,

I've recently come across some interesting behavior in a script I wrote to monitor a build process.  The actual build command (a top-level make, on RedHat Linux) is spawned as a pipe so the script can monitor it.  At the end of the build, after a tarball is created, the entire source tree is CVS-tagged.  This tagging takes a lot of time, so I then fork a child process to wait for the build to complete, to allow the parent to do other processing.  What's happening, though, is that the parent is somehow getting blocked.

I discovered the problem goes away when the filehandle used for the IO::Select (to read output from the build) is made global, which otherwise is constructed as a deeply-bound lexical variable within the process-monitoring closure.  Can anyone shed some light on why this filehandle is somehow apparently blocking the parent process after the fork, even though the parent never calls the closure again, and thus never interacts with the filehandle?

I've simplified the original program makebuild from 900 lines to 175 lines, and using a script fakebuild to simulate the build process.   When I set the variable $b_use_global_fh to zero on line 14, the parent process says "(1a) Parent about to return", but doesn't show that it has returned from the subroutine with "(2) Parent back from monitor_build()" until much later.  When $b_use_global_fh is set to 1, the parent process returns immediately, and the 2 lines appear successively in the output.

My question is "why would the behavior be different, depending on where how the FileHandle object is scoped?"

Here is the fakebuild script:

#!/usr/bin/perl -w # # Perform a 'fake build' to test the 'makebuild' script. # 060222 liverpole # + # Strict use strict; use warnings; + # Flush output $|++; + # Things to pretend to build my @modules = qw( admin drivers tools ); + # Do a simulated 'make clean' map { unlink("$_.txt") } @modules; # Unlink each module's logfile unlink "cvstag.txt"; # This one's special + # Pretend to build everything sleep 1; foreach (@modules) { print STDERR "Building module '$_' ...\n"; system("touch $_.txt"); print STDERR " - phase 1\n"; sleep 1; print STDERR " - phase 2\n"; sleep 1; print STDERR " - phase 3\n"; sleep 1; } + # Pretend to perform the tagging procedure print STDERR "CVS tagging ...\n"; system("touch cvstag.txt"); for (my $i = 1; $i <= 16; $i++) { sleep 1; print STDERR "Tagging file $i\n"; }

And here is the makebuild script:

#!/usr/bin/perl -w # # Test program to demonstrate the differing behavior when a global # filehandle is used, vs. a deeply-bound lexical in a forked closure. # # 060222 liverpole # # Strict use strict; use warnings; # User-defined my $b_use_global_fh = 0; # Libraries use File::Basename; use FileHandle; use IO::Select; # Declarations sub monitor_build; sub monitor_logfiles; sub system_command; # Globals $| = 1; my $iam = basename $0; my $global_fh; #################### ### Main program ### #################### # Remove the previous build system("rm -f *.txt"); # Construct a global filehandle $global_fh = new FileHandle; # Perform build -- fork occurs within subroutine, and only parent retu +rns print STDERR "Starting build\n"; monitor_build("./fakebuild"); print STDERR "\e[101m(2) Parent back from monitor_build()\e[m\n"; # Parent can now tend to other business... print STDERR "Notifying users of build completion ...\n"; sleep 1; print STDERR "Adding build version to Bugzilla ...\n"; sleep 1; print STDERR "Building .iso images ...\n"; sleep 1; ################### ### Subroutines ### ################### # # Inputs: $1 ... the build command # # Results: Issues the build command to the system and monitors its p +rogress. # sub monitor_build { my ($bld_cmd) = @_; my @logfiles = qw( admin drivers tools cvstag ); my $plogs = { map { "$_" . ".txt", 1 } @logfiles }; my $psyscmd = system_command("$bld_cmd 2>&1"); my $b_finished = 0; while (1) { my $ptext = $psyscmd->(8); last unless $ptext; foreach my $line (@$ptext) { print "Text from build [$line]\n"; } if (!$b_finished && monitor_logfiles($plogs)) { # The build has finished (except for the CVS tagging phase +), # so we fork, to let the parent return and complete other +tasks # (eg. user-notify, adding version number to Bugzilla, etc +.) # The child continues until the tagging is complete. We a +lso # set $b_finished so this block doesn't get executed again +. # my $pid = fork; defined($pid) or die "$iam: unable to fork!\n"; if ($pid) { # Parent print STDERR "\e[101m(1a) Parent about to return\e[m\n +"; return; } # Child print STDERR "\e[102m(1b) Child continues tagging\e[m\n"; $b_finished = 1; } select(undef, undef, undef, 0.250); } print STDERR "\e[102m(3) Child is finished -- exiting\e[m\n"; exit; # The build finished -- no need for the child to continue } # # Inputs: $1 ... a pointer to the hash of logfile names # # Outputs: $1 ... nonzero if CVS tagging has started ("cvstag.txt" h +as # been created), zero otherwise. # # Results: finds any build logfiles have been written to, logs their + names # and date, and removes them from the hash. # sub monitor_logfiles { my ($plogs) = @_; my %modified; foreach my $logfile (keys %$plogs) { (-e $logfile) and $modified{$logfile} = (stat($logfile))[9]; } my $b_cvs_tagging = 0; map { print STDERR "Started log '$_'\n"; delete $plogs->{$_}; ($_ eq 'cvstag.txt') and $b_cvs_tagging = 1; } sort { $modified{$a} <=> $modified{$b} } (keys %modified); return $b_cvs_tagging; } # # Inputs: $1 ... a command to issue to the shell # # Outputs: $1 ... a closure which reads successive lines of process +output # # Results: Opens an output pipe from the given command and returns a + closure # which reads non-blocking text from the pipe and returns a + pointer # to it. The closure takes a single argument -- the maximu +m number # of lines of text to read on each call (0 = unlimited). A + zero is # returned when the command finishes. # sub system_command { my ($cmd) = @_; # Create a pipe to the command my $fh = $b_use_global_fh? $global_fh: new FileHandle; open($fh, "$cmd|") or die "$iam: Cannot pipe to command '$cmd' ($ +!)\n"; # Create a Select object my $select = IO::Select->new(); $select->add($fh); my $b_done_syscmd = 0; # Create the monitoring closure my $psub = sub { my ($maxlines) = @_; $b_done_syscmd and return 0; my @lines; while (1) { last unless $select->can_read(0); defined(my $line = <$fh>) or $b_done_syscmd = 1; last if $b_done_syscmd; chomp $line; push @lines, $line; last if ($maxlines > 0 && @lines == $maxlines); select(undef, undef, undef, 0.250); } return \@lines; }; return $psub; }

@ARGV=split//,"/:L"; map{print substr crypt($_,ord pop),2,3}qw"PerlyouC READPIPE provides"

In reply to Why is a deeply-bound lexical in a forked closure blocking the parent process? by liverpole

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.