I am writing a client-server application that uses $SIG{ALRM} to 'time-out' commands that take too long. Early on in the writing of this application, I used the following code to implement this:
$SIG{ALRM} = sub { die "TIMEOUT" }; eval { alarm(ON); open COMMAND, "$command |" or die "Can't fork: $!\n"; $output .= $_ while (<COMMAND>); close COMMAND or die "Can't close pipe: $!\n"; alarm(OFF); }; if ($@ =~ /TIMEOUT/) { # do stuff }
This worked fine in my first version. I change ON (which is a constant) to 1 and and slow commands like 'top' will trigger the alarm, which allows me to gracefully catch such erroneous behavior without crashing the client or the server.

Well, time moved on and I switched to verion 2. I decided to check my time-out code again, and this time the client would hang until I interupted the server. Hmmm, sounded like a buffering problem - but it wasn't.

Eventually I changed the above code to:

open COMMAND, "$command |" or die "Can't fork: $!\n"; eval { alarm(ON); $output .= $_ while (<COMMAND>); alarm(OFF); }; close COMMAND; #notice no 'or die stuff' here anymore
and everything went back to peachy keen (or so it seems . . .)

What is bugging me is that if I use '|| die' after the close, the server indeed dies. But if I remove the close line all together, then the client will hang. I could use a warn instead of a die, but that really does me no good - the time-out will get logged by the application anyways.

If anybody can offer any insight into this, I will greatly appreciate it.

Jeff

L-LL-L--L-LL-L--L-LL-L--
-R--R-RR-R--R-RR-R--R-RR
F--F--F--F--F--F--F--F--
(the triplet paradiddle)

In reply to Close the pipe before the alarm goes off! by jeffa

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.