summaryrefslogtreecommitdiff
path: root/fml/lib/IO/t/file_lock.pl
blob: a08ff7e2d39f43929d1283c0134f6be234fbdf2e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#-*- perl -*-
#
#  Copyright (C) 2004 Ken'ichi Fukamachi
#   All rights reserved. This program is free software; you can
#   redistribute it and/or modify it under the same terms as Perl itself.
#
# $FML: lock.pl,v 1.1 2004/04/10 07:40:02 fukachan Exp $
#

use strict;
use Carp;

my $debug = 0;
my $i     = 0;
my $file  = "/tmp/io.adapter.$$";
my $map   = "file:$file";
my %log   = ();
my %pid   = ();

### MAIN ###
use FML::Test::Utils;
my $tool = new FML::Test::Utils;
$tool->set_title("file lock/unlock");

use IO::Adapter;

for my $i (0 .. 5) {
    my $obj = new IO::Adapter $map;

    my $pid = fork();
    $pid{ $pid } = 1;
    if ($pid == 0) {
	my $t;
	my $ok;

	if ($obj->lock()) {
	    $t = time;
	    $log{ $i } .= "locked\t";
	    $ok++;
	}

	sleep(rand(5));
	if ($obj->unlock()) {
	    $t = time - $t;
	    $log{ $i } .= "$t\tunlocked\n";
	    $ok++;
	}

	print STDERR "$i [$$]\t$log{ $i }" if $debug;
	if ($ok == 2) {
	    $tool->print_ok("[$$] (wait for $t sec)");
	}
	else {
	    $tool->print_error("[$$] (wait for $t sec)");
	}

	exit(0);
    }
}

# Wait for the child to terminate.
{
    my $dying;

  WAIT:
    while (($dying = wait()) != -1) {
	$pid{ $dying } = 0;

	my $found = 0;
	for my $i (keys %pid) {
	    $found++ if $pid{ $i };
	}

	last WAIT if $found;
    }
}

sleep 20;

exit 0;