The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.
#!/usr/bin/perl
$| = 1;

# Note that because fork loses test count we do not use Test::More

use strict;

BEGIN { print "1..8\n"; }

use File::Temp;

# OO interface

my $file = File::Temp->new(CLEANUP=>1);

myok( 1, -f $file->filename, "OO File exists" );

my $children = 2;
for my $i (1 .. $children) {
  my $pid = fork;
  die "Can't fork: $!" unless defined $pid;
  if ($pid) {
    # parent process
    next;
  } else {
    # in a child we can't keep the count properly so we do it manually
    # make sure that child 1 dies first
    srand();
    my $time = (($i-1) * 5) +int(rand(5));
    print "# child $i sleeping for $time seconds\n";
    sleep($time);
    my $count = $i + 1;
    myok( $count, -f $file->filename(), "OO file present in child $i" );
    print "# child $i exiting\n";
    exit;
  }
}

while ($children) {
    wait;
    $children--;
}



myok( 4, -f $file->filename(), "OO File exists in parent" );

# non-OO interface

my ($fh, $filename) = File::Temp::tempfile( CLEANUP => 1 );

myok( 5, -f $filename, "non-OO File exists" );

$children = 2;
for my $i (1 .. $children) {
  my $pid = fork;
  die "Can't fork: $!" unless defined $pid;
  if ($pid) {
    # parent process
    next;
  } else {
    srand();
    my $time = (($i-1) * 5) +int(rand(5));
    print "# child $i sleeping for $time seconds\n";
    sleep($time);
    my $count = 5 + $i;
    myok( $count, -f $filename, "non-OO File present in child $i" );
    print "# child $i exiting\n";
    exit;
  }
}

while ($children) {
    wait;
    $children--;
}
myok(8, -f $filename, "non-OO File exists in parent" );


# Local ok sub handles explicit number
sub myok {
  my ($count, $test, $msg) = @_;

  if ($test) {
    print "ok $count - $msg\n";
  } else {
    print "not ok $count - $msg\n";
  }
  return $test;
}