1Simple(3) User Contributed Perl Documentation Simple(3)
2
3
4
6 LockFile::Simple - simple file locking scheme
7
9 use LockFile::Simple qw(lock trylock unlock);
10
11 # Simple locking using default settings
12 lock("/some/file") || die "can't lock /some/file\n";
13 warn "already locked\n" unless trylock("/some/file");
14 unlock("/some/file");
15
16 # Build customized locking manager object
17 $lockmgr = LockFile::Simple->make(-format => '%f.lck',
18 -max => 20, -delay => 1, -nfs => 1);
19
20 $lockmgr->lock("/some/file") || die "can't lock /some/file\n";
21 $lockmgr->trylock("/some/file");
22 $lockmgr->unlock("/some/file");
23
24 $lockmgr->configure(-nfs => 0);
25
26 # Using lock handles
27 my $lock = $lockmgr->lock("/some/file");
28 $lock->release;
29
31 This simple locking scheme is not based on any file locking system
32 calls such as flock() or lockf() but rather relies on basic file system
33 primitives and properties, such as the atomicity of the write() system
34 call. It is not meant to be exempt from all race conditions, especially
35 over NFS. The algorithm used is described below in the ALGORITHM
36 section.
37
38 It is possible to customize the locking operations to attempt locking
39 once every 5 seconds for 30 times, or delete stale locks (files that
40 are deemed too ancient) before attempting the locking.
41
43 The locking alogrithm attempts to create a lockfile using a temporarily
44 redefined umask (leaving only read rights to prevent further create
45 operations). It then writes the process ID (PID) of the process and
46 closes the file. That file is then re-opened and read. If we are able
47 to read the same PID we wrote, and only that, we assume the locking is
48 successful.
49
50 When locking over NFS, i.e. when the one of the potentially locking
51 processes could access the lockfile via NFS, then writing the PID is
52 not enough. We also write the hostname where locking is attempted to
53 ensure the data are unique.
54
56 Customization is only possible by using the object-oriented interface,
57 since the configuration parameters are stored within the object. The
58 object creation routine "make" can be given configuration parmeters in
59 the form a "hash table list", i.e. a list of key/value pairs. Those
60 parameters can later be changed via "configure" by specifying a similar
61 list of key/value pairs.
62
63 To benefit from the bareword quoting Perl offers, all the parameters
64 must be prefixed with the "-" (minus) sign, as in "-format" for the
65 format parameter.. However, when querying the object, the minus must
66 be omitted, as in "$obj->format".
67
68 Here are the available configuration parmeters along with their
69 meaning, listed in alphabetical order:
70
71 autoclean
72 When true, all locks are remembered and pending ones are
73 automatically released when the process exits normally (i.e.
74 whenever Perl calls the END routines).
75
76 delay
77 The amount of seconds to wait between locking attempts when the
78 file appears to be already locked. Default is 2 seconds.
79
80 efunc
81 A function pointer to dereference when an error is to be reported.
82 By default, it redirects to the logerr() routine if you have
83 Log::Agent installed, to Perl's warn() function otherwise.
84
85 You may set it explicitely to "\&LockFile::Simple::core_warn" to
86 force the use of Perl's warn() function, or to "undef" to suppress
87 logging.
88
89 ext The locking extension that must be added to the file path to be
90 locked to compute the lockfile path. Default is ".lock" (note that
91 "." is part of the extension and can therefore be changed). Ignored
92 when format is also used.
93
94 format
95 Using this parmeter supersedes the ext parmeter. The formatting
96 string specified is run through a rudimentary macro expansion to
97 derive the lockfile path from the file to be locked. The following
98 macros are available:
99
100 %% A real % sign
101 %f The full file path name
102 %D The directory where the file resides
103 %F The base name of the file
104 %p The process ID (PID)
105
106 The default is to use the locking extension, which itself is
107 ".lock", so it is as if the format used was "%f.lock", but one
108 could imagine things like "/var/run/%F.%p", i.e. the lockfile does
109 not necessarily lie besides the locked file (which could even be
110 missing).
111
112 When locking, the locking format can be specified to supersede the
113 object configuration itself.
114
115 hold
116 Maximum amount of seconds we may hold a lock. Past that amount of
117 time, an existing lockfile is removed, being taken for a stale
118 lock. Default is 3600 seconds. Specifying 0 prevents any forced
119 unlocking.
120
121 max Amount of times we retry locking when the file is busy, sleeping
122 delay seconds between attempts. Defaults to 30.
123
124 nfs A boolean flag, false by default. Setting it to true means we could
125 lock over NFS and therefore the hostname must be included along
126 with the process ID in the stamp written to the lockfile.
127
128 stale
129 A boolean flag, false by default. When set to true, we attempt to
130 detect stale locks and break them if necessary.
131
132 wafter
133 Stands for warn after. It is the number of seconds past the first
134 warning during locking time after which a new warning should be
135 emitted. See warn and wmin below. Default is 20.
136
137 warn
138 A boolean flag, true by default. To suppress any warning, set it to
139 false.
140
141 wfunc
142 A function pointer to dereference when a warning is to be issued.
143 By default, it redirects to the logwarn() routine if you have
144 Log::Agent installed, to Perl's warn() function otherwise.
145
146 You may set it explicitely to "\&LockFile::Simple::core_warn" to
147 force the use of Perl's warn() function, or to "undef" to suppress
148 logging.
149
150 wmin
151 The minimal amount of time when waiting for a lock after which a
152 first warning must be emitted, if warn is true. After that, a
153 warning will be emitted every wafter seconds. Defaults to 15.
154
155 Each of those configuration attributes can be queried on the object
156 directly:
157
158 $obj = LockFile::Simple->make(-nfs => 1);
159 $on_nfs = $obj->nfs;
160
161 Those are pure query routines, i.e. you cannot say:
162
163 $obj->nfs(0); # WRONG
164 $obj->configure(-nfs => 0); # Right
165
166 to turn of the NFS attribute. That is because my OO background chokes
167 at having querying functions with side effects.
168
170 The OO interface documented below specifies the signature and the
171 semantics of the operations. Only the "lock", "trylock" and "unlock"
172 operation can be imported and used via a non-OO interface, with the
173 exact same signature nonetheless.
174
175 The interface contains all the attribute querying routines, one for
176 each configuration parmeter documented in the CUSTOMIZING section
177 above, plus, in alphabetical order:
178
179 configure(-key => value, -key2 => value2, ...)
180 Change the specified configuration parameters and silently ignore
181 the invalid ones.
182
183 lock(file, format)
184 Attempt to lock the file, using the optional locking format if
185 specified, otherwise using the default format scheme configured in
186 the object, or by simply appending the ext extension to the file.
187
188 If the file is already locked, sleep delay seconds before retrying,
189 repeating try/sleep at most max times. If warning is configured, a
190 first warning is emitted after waiting for wmin seconds, and then
191 once every wafter seconds, via the wfunc routine.
192
193 Before the first attempt, and if hold is non-zero, any existing
194 lockfile is checked for being too old, and it is removed if found
195 to be stale. A warning is emitted via the wfunc routine in that
196 case, if allowed.
197
198 Likewise, if stale is non-zero, a check is made to see whether any
199 locking process is still around (only if the lock holder is on the
200 same machine when NFS locking is configured). Should the locking
201 process be dead, the lockfile is declared stale and removed.
202
203 Returns a lock handle if the file has been successfully locked,
204 which does not necessarily needs to be kept around. For instance:
205
206 $obj->lock('ppp', '/var/run/ppp.%p');
207 <do some work>
208 $obj->unlock('ppp');
209
210 or, using OO programming:
211
212 my $lock = $obj->lock('ppp', '/var/run/ppp.%p') ||;
213 die "Can't lock for ppp\n";
214 <do some work>
215 $lock->relase; # The only method defined for a lock handle
216
217 i.e. you don't even have to know which file was locked to release
218 it, since there is a lock handle right there that knows enough
219 about the lock parameters.
220
221 lockfile(file, format)
222 Simply compute the path of the lockfile that would be used by the
223 lock procedure if it were passed the same parameters.
224
225 make(-key => value, -key2 => value2, ...)
226 The creation routine for the simple lock object. Returns a blessed
227 hash reference.
228
229 trylock(file, format)
230 Same as lock except that it immediately returns false and does not
231 sleep if the to-be-locked file is busy, i.e. already locked. Any
232 stale locking file is removed, as lock would do anyway.
233
234 Returns a lock hande if the file has been successfully locked.
235
236 unlock(file)
237 Unlock the file.
238
240 The algorithm is not bullet proof. It's only reasonably safe. Don't
241 bet the integrity of a mission-critical database on it though.
242
243 The sysopen() call should probably be used with the "O_EXCL|O_CREAT"
244 flags to be on the safer side. Still, over NFS, this is not an atomic
245 operation anyway.
246
247 BEWARE: there is a race condition between the time we decide a lock is
248 stale or too old and the time we unlink it. Don't use "-stale" and set
249 "-hold" to 0 if you can't bear with that idea, but recall that this
250 race only happens when something is already wrong. That does not make
251 it right, nonetheless. ;-)
252
254 Raphael Manfredi <Raphael_Manfredi@pobox.com>
255
257 File::Flock(3).
258
259
260
261perl v5.38.0 2023-07-20 Simple(3)