#!/usr/bin/perl -w
use strict;
use warnings;

use File::Temp;

my ($buf_file) = @ARGV;
my $fh;

$fh = File::Temp->new() if !defined $buf_file;
open my $fh, "+>", $buf_file if !$fh;

my $block_size = 64*1024;

my $block;

my $child = fork();
if ($child == 0) {
	file_to_out();
} else {
	in_to_file($child);
}

my $done = 0;

$SIG{USR1} = sub { };   # TODO will 'IGNORE' do, will it still interrupt sleep?
$SIG{USR2} = sub { $done = 1; };

sub in_to_file {
	my ($child) = @_;
	while (read STDIN, $block, $block_size) {
		print $fh $block
			or die "$!\n";
		kill 'USR1', $child;
	}
	die "$!\n" if $!;
	kill 'USR2', $child;
}

sub file_to_out {
	while (!$done) {
		while (read $fh, $block, $block_size) {
			
		}
		sleep;
}

while (read STDIN, $block, $block_size) {
	print $fh $block
		or die "$!\n";
}
die "$!\n" if $!;
