In the child, execute
open STDOUT, "|-", "tee", $output
or die "$0: failed to start tee: $!";
If you don't want to use tee
for some reason, you could use a poor man's version by forking another child via open STDOUT, "|-"
and doing the duplication in the grandchild:
#! /usr/bin/perl
use warnings;
use strict;
my $pid = fork;
die "$0: fork: $!" unless defined $pid;
if ($pid) {
waitpid $pid, 0;
}
else {
my $pid = open STDOUT, "|-";
die "$0: fork: $!" unless defined $pid;
select STDOUT; $| = 1; # disable STDOUT buffering
if ($pid) {
print "Hiya!\n";
system "echo Howdy";
close STDOUT or warn "$0: close: $!";
exit 0;
}
else {
open my $fh, ">", "/tmp/other-output" or die "$0: open: $!";
my $status;
while ($status = sysread STDIN, my $data, 8192) {
syswrite $fh, $data and print $data or die "$0: output failed: $!";
}
die "$0: sysread: $!" unless defined $status;
close $fh or warn "$0: close: $!";
exit 0;
}
}
Sample run:
$ ./owntee
Hiya!
Howdy
$ cat other-output
Hiya!
Howdy