#!/usr/bin/perl -w use Fcntl ':flock'; use POSIX "sys_wait_h"; my $file = '/tmp/test-file.txt'; my $try; my $pid = fork(); if ($pid == 0) { #this is the child #Go to sleep and let the parent lock the file print "Child ($$) going to sleep for a bit...\n"; sleep(3); print "Child ($$) woke up!\n"; #Wake up and try to open and lock the file print "Child ($$) attempting to open for writing...\n"; if (open CWRITER, ">$file"){ print "Child ($$) completed open for writing\n"; print "Child ($$) closing filehandle.\n"; close CWRITER; print "Child ($$) closed filehandle. Exiting.\n"; } else { print "Child ($$) unable to open for appending: $!\n"; } exit; } else { #this is the parent #open a filehandle and lock it with LOCK_EX print "Parent ($$) attempting to open file\n"; if (open PWRITER, ">$file"){ print "Parent ($$) opened file, attempting LOCK_EX\n"; my $try = flock(PWRITER, LOCK_EX) or warn "Parent ($$) can't flock: $!\n"; print "Parent ($$) try for LOCK_EX is '$try'\n"; print "Parent ($$) printing to file\n"; print PWRITER "Parent says hello.\n"; print "Parent ($$) done writing, closing filehandle.\n"; close PWRITER; print "Parent ($$) closed filehandle, now reopening as reader.\n"; if (open PREADER, "$file") { print "Parent ($$) opened file for reading. Requesting LOCK_EX.\n"; flock(PREADER, LOCK_EX) or warn "Parent ($$) unable to LOCK_EX: $!, $?\n"; print "Parent ($$) got LOCK_EX.\n"; print "Parent ($$) going to sleep.\n"; sleep(10); print "Parent ($$) woke up!\n"; print "Parent ($$) reading now...\n"; my @lines = ; print "Parent ($$) read:\n@lines\n"; print "Parent ($$) closing PREADER\n"; close PREADER; print "Parent ($$) closed PREADER.\n"; } else { print "Parent unable to open file for read: $!\n"; } } else { warn "Parent ($$) couldn't open '$file' for reading: $!\n"; } my $waiter = 1; while ($waiter > 0){ #try to reap the child PID $waiter = waitpid($pid, &WNOHANG); if ($waiter == -1){ print "Waiter got -1: $?\n"; } elsif ($waiter == 0) { print "Waiter got 0, $pid still alive...\n"; } elsif ($waiter > 0) { print "Waiter got $waiter, $?\n"; } else { print "Waiter got something odd: '$waiter','$?'\n"; } sleep(2); } print "Parent ($$) done reaping child $pid\n"; } print "$$ Exiting\n";