Minimal code that demonstrates the problem:

file: child.pl

#!/usr/bin/perl $| = 1; sleep 10; print "x\n"; while (1) { sleep 10; }

file: main.pl

#!/usr/bin/perl open my $fh, "./child.pl |"; close $fh;

Running mail.pl reliably exits after 10 seconds, i.e. right after child.pl has sent its first output. If you remove the print line from child.pl, the main program will never exit.

I'm interested in two things: an explanation of why the program behaves this way, and a solution to the concrete problem this is causing me, described below.

Here's the relevant piece of the real code:
... my $active = 1; my $timeout = 20; my $an; open my $fh, "tcpdump -nn -l -e dst 224.111.111.112 and not igmp |"; $read_set->add($fh); while ($active) { my ($rh_set) = IO::Select->select($read_set, undef, undef, 1); if (defined $rh_set) { if ($_ = <$fh>) { # do some parsing on the line $an = $1; last; } else { # tcpdump died. real code will sleep 2 seconds # and then close and reopen $fh here } } if (--$timeout == 0) { $active=0; } } close $fh;
What I want is to either capture the first packet that passes the tcpdump filter ($an set to the source IP), or if no packet comes in before the timeout is over, leave the loop with $an still undefined.

Currently I'm working around this problem by explicitely starting tcpdump in a fork()ed child and killing it after the timeout. This works but I have to use a temp file or a pipe to store the tcpdump output, and it's a lot more code than something like the above.

I'm open to whatever solutions the wise monks can come up with, even if it means going about it a whole other way.


In reply to How to end a process started with open "cmd |" before it has output by Crackers2

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.