#!/usr/bin/perl -w
use strict;
use File::Temp qw(tempfile);

if (@ARGV) {
    print STDERR "Child running\n";
    my $file = shift || die "$0 needs a file argument";
    open(STDOUT, ">", $file) || die "Could not create $file: $!\n";
    $| = 1;
    print while <>;
    print STDERR "Child done\n";
    exit;    
}

my $curpos = 0;
my $have = "";
my $tmp;

my $MAX_WAIT = 5;
sub tail {
    my $target = shift;
    my $start = time;
    until (ref($target) ? $have =~ s/^$target// : $have =~ s/^\Q$target//) {
        local $_;
        seek($tmp, $curpos, 0) || die "Seek error: $!";
        $have .= $_ while <$tmp>;
        $curpos = tell($tmp);
        my $now = time;
        if (!ref($target) && $target !~ /^\Q$have/ ||
            $now > $start + $MAX_WAIT) {
            die("Could not find '$target' in '$have'");
        }
        sleep 1 if $now > $start+1;
    }
    print STDERR "All ok!\n";
}

my $tmp_name = "blub";
(my $tfh, $tmp_name) = tempfile;
open($tmp, "<", $tmp_name) || die "Could not open $tmp_name: $!";
print STDERR "temp file is $tmp_name\n";
open(my $pipe, "|-", "$^X $0 $tmp_name") || die "Could not start $0: $!";
my $fh = select($pipe);
$| = 1;
select($fh);
print $pipe "foo\nbar\n";
tail("foo\nbar\n");
