#!/usr/bin/perl -w
use strict;
use POSIX qw( mkfifo );

my $message = <<EOM;
Hello, World.
That is all
EOM

my $testno=1;
#unbuffer outputs
select STDERR; $|=1; select STDOUT; $|=1;

sub check {
	my ($stat,$msg)=@_;
	printf "Test $testno had status %s;%s\n", 
		$stat?"pass":"fail", 
		$msg?"(msg=$msg)":"";
	++$testno;
	return $stat;
}


my $fifo = 'test_fifo';
unlink $fifo if (-e $fifo); 					#prior hang?: cleanup



check( mkfifo($fifo, 0700), "Created fifo $fifo" ) or warn $!;

my $pid = fork;
if ($pid) {

	check( 1 ,"parent: forked ok, about to open fifo");
    open my $reader, '<', $fifo or die "$$: Couldn't read '$fifo': $!";


	#### cygwin never gets here....


	check( 1, "parent: after open about to read from child");
	my $child_msg = <$reader>;

	check ( ($child_msg eq $message) ,
		"parent: received msg from child, closing reader...");
    close $reader;

	check( 1 ,"parent: closed reader, about to wait on child");
    check( (waitpid($pid,0) > 0), "waitpid($pid) > 0");

    check(unlink($fifo), "removed $fifo") or warn $!;

} elsif (defined $pid) {
    
	check( 1, "child: fork ok, about to open fifo");
    open my $writer, '>', $fifo or die "$$: Couldn't write '$fifo': $!";

	#### cygwin never gets here....

	check (1, "child: after opening fifo for write; about to print");
    print $writer $message;

    # diag "$$: Wrote ", length $message, " bytes to fifo";
	check (1, "child: wrote; about to close");	
    close $writer;

	check (1, "child: closed; about to exit");
    exit 0;

} else {
    die "$0: fork failed: $!";
}
