| 1 | #!/usr/bin/perl | ||
| 2 | |||
| 3 | # (c) 2003 Luis E. Muñoz. This code is provided AS IS, with absolutely no | ||
| 4 | # warranty. It can be distributed under the same terms as Perl itself. | ||
| 5 | |||
| 6 | # This script tests the behavior of flock() in your installation. | ||
| 7 | |||
| 8 | use strict; | ||
| 9 | use warnings; | ||
| 10 | use IO::File; | ||
| 11 | use Fcntl qw(:flock); | ||
| 12 | |||
| 13 | our $lock_file = 'test_lck'; | ||
| 14 | |||
| 15 | # Get rid of our garbage | ||
| 16 | END { | ||
| 17 | unlink $lock_file; | ||
| 18 | }; | ||
| 19 | |||
| 20 | our %fh; | ||
| 21 | my $id = 'A'; | ||
| 22 | my $pid; | ||
| 23 | my $buf = 'nothing'; | ||
| 24 | |||
| 25 | $|++; | ||
| 26 | |||
| 27 | # Spawn one helpful kid... | ||
| 28 | |||
| 29 | while (($pid = fork()) == -1) | ||
| 30 | { | ||
| 31 | sleep 2; | ||
| 32 | } | ||
| 33 | |||
| 34 | unless ($pid) | ||
| 35 | { # This is our child | ||
| 36 | ++ $id; | ||
| 37 | |||
| 38 | END {}; | ||
| 39 | |||
| 40 | my $fh = new IO::File "$lock_file", O_RDWR | O_CREAT | ||
| 41 | or die "Failed to open $lock_file: $!\n"; | ||
| 42 | |||
| 43 | print "$id: about to lock...\n"; | ||
| 44 | |||
| 45 | unless (flock($fh, LOCK_EX | LOCK_NB)) | ||
| 46 | { | ||
| 47 | die "$id: Failed to acquire lock: $!\n"; | ||
| 48 | } | ||
| 49 | |||
| 50 | print "$id: done\n"; | ||
| 51 | |||
| 52 | print "$id: wrote\n"; | ||
| 53 | $fh->syswrite("$id\n", 3); | ||
| 54 | print "$id: seeked\n"; | ||
| 55 | $fh->seek(0, 0); | ||
| 56 | sleep 3; | ||
| 57 | print "$id: read\n"; | ||
| 58 | $fh->sysread($buf, 3); | ||
| 59 | chomp $buf; | ||
| 60 | |||
| 61 | print "$id: got <$buf>\n"; | ||
| 62 | |||
| 63 | flock($fh, LOCK_UN); | ||
| 64 | $fh->close; | ||
| 65 | |||
| 66 | exit 0; | ||
| 67 | } | ||
| 68 | |||
| 69 | my $fh = new IO::File "$lock_file", O_RDWR | O_CREAT | ||
| 70 | or die "Failed to open $lock_file: $!\n"; | ||
| 71 | |||
| 72 | print "$id: about to lock...\n"; | ||
| 73 | |||
| 74 | if (flock($fh, LOCK_EX | LOCK_NB)) | ||
| 75 | { | ||
| 76 | print "$id: done\n"; | ||
| 77 | |||
| 78 | print "$id: wrote\n"; | ||
| 79 | $fh->syswrite("$id\n", 3); | ||
| 80 | print "$id: seeked\n"; | ||
| 81 | $fh->seek(0, 0); | ||
| 82 | print "$id: read\n"; | ||
| 83 | $fh->sysread($buf, 3); | ||
| 84 | sleep 2; | ||
| 85 | chomp $buf; | ||
| 86 | |||
| 87 | print "$id: got <$buf>\n"; | ||
| 88 | flock($fh, LOCK_UN); | ||
| 89 | } | ||
| 90 | else | ||
| 91 | { | ||
| 92 | print "$id: Failed to acquire lock: $!\n"; | ||
| 93 | } | ||
| 94 | |||
| 95 | $fh->close; | ||
| 96 | |||
| 97 | wait(); # Collect our child status | ||
| 98 | |||
| 99 | exit 0; | ||
| 100 |