My goal is to launch an ongoing process (such as iostat) and parse some information. Once I am done, I would like to kill iostat and gracefully close the pipe. Remember, iostat will run forever until I kill it.
If I try to kill the process before closing the pipe, close() returns a -1 for 'no children'. If I don't kill the process before closing the pipe, it returns 13 because iostat is still trying to write to my pipe. In other words, this script will always die().
How do I close this pipe gracefully?
use warnings;
use strict;
my $cmd = "iostat 1";
my $pid = open(my $pipe, "$cmd |") || die "ERROR: Cannot open pipe to iostat process: $!\n";
my $count = 0;
while (<$pipe>){
if ($count > 2){
kill(9, $pid); # if I execute these two lines, close() returns -1
waitpid($pid, 0); # otherwise it returns 13
last;
}
$count++;
}
close($pipe) || die "ERROR: Cannot close pipe to iostat process: $! $?\n";
exit 0;