use Fcntl qw(LOCK_EX LOCK_UN); #select H; $|=1; select STDOUT; # Uncomment to fix $| = 1; open H,'>','foo.txt' or die "Can't open, $!\n"; print "Opened filehandle. Forking into 2\n"; my $pid=fork; if (!defined $pid) {die "fork failed\n"} elsif ($pid) { print "Parent will lock, wait a couple seconds, and exit\n"; flock H,LOCK_EX; print "Parent has lock\n"; print H "Parent writes to file\n"; # Comment this out to "fix" sleep 2; flock H, LOCK_UN; print "Parent byebye\n"; exit; } else { sleep 1; print "Child hi\n"; flock H,LOCK_EX; print "Child has lock\n"; flock H, LOCK_UN; print "I am the free child. Bye now!\n"; exit; }