#!/usr/bin/perl

use strict;
use warnings;

use Fcntl qw':flock';
use IO::Handle;

open(my $tmpfile, "+>", undef) or die $!;

flock $tmpfile, LOCK_EX or die $!;

defined (my $cpid = fork) or die "Fork failed: $!";

if ($cpid){
    #open my $newfile, '<', '/dev/fd/' . $tmpfile->fileno or die $!; # Works, but not completely portable
    open my $newfile, '<', '/dev/fd/' . $tmpfile->fileno or die $!;
    # open my $newfile, '+>&' . $tmpfile->fileno or die $!;
    undef $tmpfile;
    print "$$: parent reopen\n";

    flock $newfile, LOCK_SH or die $!;
    print "$$: parent lock\n";
}
else {
    sleep 2;
    print "$$: child unlock\n";
    flock $tmpfile, LOCK_UN or die $!;
    print "$$: child exiting\n";
}
