jeffa has asked for the wisdom of the Perl Monks concerning the following question:

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)

Replies are listed 'Best First'.
Re: Close the pipe before the alarm goes off!
by Fastolfe (Vicar) on Dec 12, 2000 at 00:28 UTC
    Note that close will return a false value if, in the case of the IPC version of open that you're using, the command you're executing returns a non-zero exit status (indicating an error). You may get output, but if the program is exiting in error, you will catch this with the result of your close. From perlfunc:
    If the file handle came from a piped open `close' will additionally return false if one of the other system calls involved fails or if the program exits with non-zero status. (If the only problem was that the program exited non-zero `$!' will be set to `0'.) Closing a pipe also waits for the process executing on the pipe to complete, in case you want to look at the output of the pipe afterwards, and implicitly puts the exit status value of that command into `$?'. ... close OUTPUT # wait for sort to finish or warn $! ? "Error closing sort pipe: $!" : "Exit status $? from sort";