Re: weird behavior with open and pipe
- From: anno4000@xxxxxxxxxxxxxxxxxxxxxxx (Anno Siegel)
- Date: 30 Jun 2005 15:38:56 GMT
Moritz Karbach <moritz.karbach@xxxxxxx> wrote in comp.lang.perl.misc:
> Hi,
>
> I'm still tuning the run()-function of my Command class (see some older
> postings of mine, if you like).
>
> I'm using
>
> open($fh_child,"-|");
>
> to fork and to open a pipe to the child, which then exec's a system command.
> The parent uses
>
> my @output = <$fh_child>;
> close($fh_child);
>
> to receive the output. Here is the problem:
>
> If the childs executes a certain system command and the system command gets
> killed externally (by a watchdog), sometimes the parent doesn't receive any
> output! Yes, I'm sure, that the system command has written something to std
> out before it got killed.
Buffering. The output is still in a buffer when the program gets killed,
so the data is lost. At least, that's consistent with what you're
seeing.
> The weird thing is, that if I execute something like
>
> <test.sh>
> #!/bin/bash
> echo "this is a test"
> sleep 10
> </test.sh>
>
> and if I kill the process after say 5 seconds, the parent indeed receives
> the line "this is a test"!
A shell script is a bad approximation for a single process, it runs
as a series of sub-processes, held together by the shell. You probably
killed the shell, which is neither the process that echoed, nor the
one that sleeps. A perl program would be a better approximation (store
in /tmp/prog):
#!/usr/local/bin/perl
use strict; use warnings;
$| = 1; # auto-flush -- comment this out
print "this is a test\n";
sleep 5;
This runs all in a single process. The parent program
#!/usr/local/bin/perl
use strict; use warnings; $| = 1;
my $pid_child = open my $fh_child, '-|', '/tmp/prog' or
die "pipe open: $!";
sleep 2;
kill TERM => $pid_child or die;
print while <$fh_child>;
still sees the output, but if you comment-out "$| = 1" and run the kid
buffered it doesn't.
Anno
.
- References:
- weird behavior with open and pipe
- From: Moritz Karbach
- weird behavior with open and pipe
- Prev by Date: Re: Problem with Net::SSH Perl
- Next by Date: FAQ 5.37 How do I select a random line from a file?
- Previous by thread: weird behavior with open and pipe
- Next by thread: FAQ 5.37 How do I select a random line from a file?
- Index(es):
Relevant Pages
|
|