summaryrefslogtreecommitdiff
path: root/lib/File/Temp/t/lock.t
blob: ff8c7f954d75f488fc4501f4547972561443a788 (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
#!perl -w
# Test O_EXLOCK

use Test::More;
use strict;
use Fcntl;

BEGIN {
# see if we have O_EXLOCK
  eval { &Fcntl::O_EXLOCK; };
  if ($@) {
    plan skip_all => 'Do not seem to have O_EXLOCK';
  } else {
    plan tests => 4;
    use_ok( "File::Temp" );
  }
}

# Need Symbol package for lexical filehandle on older perls
require Symbol if $] < 5.006;

# Get a tempfile with O_EXLOCK
my $fh = new File::Temp();
ok( -e "$fh", "temp file is present" );

# try to open it with a lock
my $flags = O_CREAT | O_RDWR | O_EXLOCK;

my $timeout = 5;
my $status;
eval {
   local $SIG{ALRM} = sub { die "alarm\n" }; # NB: \n required
   alarm $timeout;
   my $newfh;
   $newfh = &Symbol::gensym if $] < 5.006;
   $status = sysopen($newfh, "$fh", $flags, 0600);
   alarm 0;
};
if ($@) {
   die unless $@ eq "alarm\n";   # propagate unexpected errors
   # timed out
}
ok( !$status, "File $fh is locked" );

# Now get a tempfile with locking disabled
$fh = new File::Temp( EXLOCK => 0 );

eval {
   local $SIG{ALRM} = sub { die "alarm\n" }; # NB: \n required
   alarm $timeout;
   my $newfh;
   $newfh = &Symbol::gensym if $] < 5.006;
   $status = sysopen($newfh, "$fh", $flags, 0600);
   alarm 0;
};
if ($@) {
   die unless $@ eq "alarm\n";   # propagate unexpected errors
   # timed out
}
ok( $status, "File $fh is not locked");