",$filename or die...">

Perl redirect stdout but keep parent

In perl after fork()ing, I can redirect the child stdout to such a file

open STDOUT,">",$filename or die $!

I am wondering if there is a way to β€œcopy it” by keeping stdout on the parent stdout, but also copying to the specified file. This should be done in such a way that buffering is not required, and the user sees console output in real time. It will be like unix tee. But ideally, this solution would not include third-party libraries.

+3
source share
2 answers

In the child case, run

open STDOUT, "|-", "tee", $output
  or die "$0: failed to start tee: $!";

tee - , , open STDOUT, "|-" :

#! /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;
  }
}

:

$ ./owntee 
Hiya!
Howdy

$ cat other-output 
Hiya!
Howdy
+3

, , , STDOUT, :

open my $destfile, '>', $path or die "Can't open destination file: $!\n";

my $pid = open my $child, '-|';
defined $pid or die "Can't fork: $!\n";

if ($pid == 0) {
    # Child process:
    print "I'm the child!\n";
    close $destfile;
    #  do whatever
    exit;
}

# Parent process:

while (<$child>) {
    print STDOUT    $_;
    print $destfile $_;
}

close $child;
close $destfile;

, , , , .

0

Source: https://habr.com/ru/post/1755364/


All Articles