1NAME
2
3 IPC::Shareable - Use shared memory backed variables across processes
4
5SYNOPSIS
6
7 use IPC::Shareable qw(:lock);
8
9 my $href = IPC::Shareable->new(%options);
10
11 # ...or
12
13 tie SCALAR, 'IPC::Shareable', OPTIONS;
14 tie ARRAY, 'IPC::Shareable', OPTIONS;
15 tie HASH, 'IPC::Shareable', OPTIONS;
16
17 (tied VARIABLE)->lock;
18 (tied VARIABLE)->unlock;
19
20 (tied VARIABLE)->lock(LOCK_SH|LOCK_NB)
21 or print "Resource unavailable\n";
22
23 my $segment = (tied VARIABLE)->seg;
24 my $semaphore = (tied VARIABLE)->sem;
25
26 (tied VARIABLE)->remove;
27
28 IPC::Shareable->clean_up;
29 IPC::Shareable->clean_up_all;
30
31 # Ensure only one instance of a script can be run at any time
32
33 IPC::Shareable->singleton('UNIQUE SCRIPT LOCK STRING');
34
35DESCRIPTION
36
37 IPC::Shareable allows you to tie a variable to shared memory making it
38 easy to share the contents of that variable with other Perl processes
39 and scripts.
40
41 Scalars, arrays, hashes and even objects can be tied. The variable
42 being tied may contain arbitrarily complex data structures - including
43 references to arrays, hashes of hashes, etc.
44
45 The association between variables in distinct processes is provided by
46 GLUE (aka "key"). This is any arbitrary string or integer that serves
47 as a common identifier for data across process space. Hence the
48 statement:
49
50 tie my $scalar, 'IPC::Shareable', { key => 'GLUE STRING', create => 1 };
51
52 ...in program one and the statement
53
54 tie my $variable, 'IPC::Shareable', { key => 'GLUE STRING' };
55
56 ...in program two will create and bind $scalar the shared memory in
57 program one and bind it to $variable in program two.
58
59 There is no pre-set limit to the number of processes that can bind to
60 data; nor is there a pre-set limit to the complexity of the underlying
61 data of the tied variables. The amount of data that can be shared
62 within a single bound variable is limited by the system's maximum size
63 for a shared memory segment (the exact value is system-dependent).
64
65 The bound data structures are all linearized (using Raphael Manfredi's
66 Storable module or optionally JSON) before being slurped into shared
67 memory. Upon retrieval, the original format of the data structure is
68 recovered. Semaphore flags can be used for locking data between
69 competing processes.
70
71OPTIONS
72
73 Options are specified by passing a reference to a hash as the third
74 argument to the tie() function that enchants a variable.
75
76 The following fields are recognized in the options hash:
77
78 key
79
80 key is the GLUE that is a direct reference to the shared memory segment
81 that's to be tied to the variable.
82
83 If this option is missing, we'll default to using IPC_PRIVATE. This
84 default key will not allow sharing of the variable between processes.
85
86 Default: IPC_PRIVATE
87
88 create
89
90 create is used to control whether the process creates a new shared
91 memory segment or not. If create is set to a true value, IPC::Shareable
92 will create a new binding associated with GLUE as needed. If create is
93 false, IPC::Shareable will not attempt to create a new shared memory
94 segment associated with GLUE. In this case, a shared memory segment
95 associated with GLUE must already exist or we'll croak().
96
97 Defult: false
98
99 exclusive
100
101 If exclusive field is set to a true value, we will croak() if the data
102 binding associated with GLUE already exists. If set to a false value,
103 calls to tie() will succeed even if a shared memory segment associated
104 with GLUE already exists.
105
106 See "graceful" for a silent, non-exception exit if a second process
107 attempts to obtain an in-use exclusive segment.
108
109 Default: false
110
111 graceful
112
113 If exclusive is set to a true value, we normally croak() if a second
114 process attempts to obtain the same shared memory segment. Set graceful
115 to true and we'll exit silently and gracefully. This option does
116 nothing if exclusive isn't set.
117
118 Useful for ensuring only a single process is running at a time.
119
120 Default: false
121
122 warn
123
124 When set to a true value, graceful will output a warning if there are
125 process collisions.
126
127 Default: false
128
129 mode
130
131 The mode argument is an octal number specifying the access permissions
132 when a new data binding is being created. These access permission are
133 the same as file access permissions in that 0666 is world readable,
134 0600 is readable only by the effective UID of the process creating the
135 shared variable, etc.
136
137 Default: 0666 (world read and writeable)
138
139 size
140
141 This field may be used to specify the size of the shared memory segment
142 allocated.
143
144 The maximum size we allow by default is ~1GB. See the "limit" option to
145 override this default.
146
147 Default: IPC::Shareable::SHM_BUFSIZ() (ie. 65536)
148
149 limit
150
151 This field will allow you to set a segment size larger than the default
152 maximum which is 1,073,741,824 bytes (approximately 1 GB). If set, we
153 will croak() if a size specified is larger than the maximum. If it's
154 set to a false value, we'll croak() if you send in a size larger than
155 the total system RAM.
156
157 Default: true
158
159 destroy
160
161 If set to a true value, the shared memory segment underlying the data
162 binding will be removed when the process that initialized the shared
163 memory segment exits (gracefully)[1].
164
165 Only those memory segments that were created by the current process
166 will be removed.
167
168 Use this option with care. In particular you should not use this option
169 in a program that will fork after binding the data. On the other hand,
170 shared memory is a finite resource and should be released if it is not
171 needed.
172
173 Default: false
174
175 tidy
176
177 For long running processes, set this to a true value to clean up
178 unneeded segments from nested data structures. Comes with a slight
179 performance hit.
180
181 Default: false
182
183 serializer
184
185 By default, we use Storable as the data serializer when writing to or
186 reading from the shared memory segments we create. For cross-platform
187 and cross-language purposes, you can optionally use JSON for this task.
188
189 Send in either json or storable as the value to use the respective
190 serializer.
191
192 Default: storable
193
194 Default Option Values
195
196 Default values for options are:
197
198 key => IPC_PRIVATE,
199 create => 0,
200 exclusive => 0,
201 mode => 0,
202 size => IPC::Shareable::SHM_BUFSIZ(),
203 limit => 1,
204 destroy => 0,
205 graceful => 0,
206 warn => 0,
207 tidy => 0,
208 serializer => 'storable',
209
210METHODS
211
212 new
213
214 Instantiates and returns a reference to a hash backed by shared memory.
215
216 Parameters:
217
218 Hash, Optional: See the "OPTIONS" section for a list of all available
219 options. Most often, you'll want to send in the key, create and destroy
220 options.
221
222 It is possible to get a reference to an array or scalar as well. Simply
223 send in either var = > 'ARRAY' or var => 'SCALAR' to do so.
224
225 Return: A reference to a hash (or array or scalar) which is backed by
226 shared memory.
227
228 singleton($glue, $warn)
229
230 Class method that ensures that only a single instance of a script can
231 be run at any given time.
232
233 Parameters:
234
235 $glue
236
237 Mandatory, String: The key/glue that identifies the shared memory
238 segment.
239
240 $warn
241
242 Optional, Bool: Send in a true value to have subsequent processes throw
243 a warning that there's been a shared memory violation and that it will
244 exit.
245
246 Default: false
247
248 ipcs
249
250 Returns the number of instantiated shared memory segments that
251 currently exist on the system.
252
253 Return: Integer
254
255 spawn(%opts)
256
257 Spawns a forked process running in the background that holds the shared
258 memory segments backing your variable open.
259
260 Parameters:
261
262 Paremters are sent in as a hash.
263
264 key => $glue
265
266 Mandatory, String/Integer: The glue that you will be accessing your
267 data as.
268
269 mode => 0666
270
271 Optional, Integer: The read/write permissions on the variable. Defaults
272 to 0666.
273
274 Example:
275
276 use IPC::Shareable;
277
278 # The following line sets things up and returns
279
280 IPC::Shareable->spawn(key => 'GLUE STRING');
281
282 Now, either within the same script, or any other script on the system,
283 your data will be available at the key/glue GLUE STRING. Call unspawn()
284 to remove it.
285
286 unspawn($key, $destroy)
287
288 This method will kill off the background process created with spawn().
289
290 Parameters:
291
292 $key
293
294 Mandatory, String/Integer: The glue (aka key) used in the call to
295 spawn().
296
297 $destroy
298
299 Optional, Bool. If set to a true value, we will remove all semaphores
300 and memory segments related to your data, thus removing the data in its
301 entirety. If not set to a true value, we'll leave the memory segments
302 in place, and you'll be able to re-attach to the data at any time.
303 Defaults to false (0).
304
305 lock($flags)
306
307 Obtains a lock on the shared memory. $flags specifies the type of lock
308 to acquire. If $flags is not specified, an exclusive read/write lock is
309 obtained. Acceptable values for $flags are the same as for the flock()
310 system call.
311
312 Returns true on success, and undef on error. For non-blocking calls
313 (see below), the method returns 0 if it would have blocked.
314
315 Obtain an exclusive lock like this:
316
317 tied(%var)->lock(LOCK_EX); # same as default
318
319 Only one process can hold an exclusive lock on the shared memory at a
320 given time.
321
322 Obtain a shared (read) lock:
323
324 tied(%var)->lock(LOCK_SH);
325
326 Multiple processes can hold a shared (read) lock at a given time. If a
327 process attempts to obtain an exclusive lock while one or more
328 processes hold shared locks, it will be blocked until they have all
329 finished.
330
331 Either of the locks may be specified as non-blocking:
332
333 tied(%var)->lock( LOCK_EX|LOCK_NB );
334 tied(%var)->lock( LOCK_SH|LOCK_NB );
335
336 A non-blocking lock request will return 0 if it would have had to wait
337 to obtain the lock.
338
339 Note that these locks are advisory (just like flock), meaning that all
340 cooperating processes must coordinate their accesses to shared memory
341 using these calls in order for locking to work. See the flock() call
342 for details.
343
344 Locks are inherited through forks, which means that two processes
345 actually can possess an exclusive lock at the same time. Don't do that.
346
347 The constants LOCK_EX, LOCK_SH, LOCK_NB, and LOCK_UN are available for
348 import using any of the following export tags:
349
350 use IPC::Shareable qw(:lock);
351 use IPC::Shareable qw(:flock);
352 use IPC::Shareable qw(:all);
353
354 Or, just use the flock constants available in the Fcntl module.
355
356 See "LOCKING" for further details.
357
358 unlock
359
360 Removes a lock. Takes no parameters, returns true on success.
361
362 This is equivalent of calling shlock(LOCK_UN).
363
364 See "LOCKING" for further details.
365
366 seg
367
368 Called on either the tied variable or the tie object, returns the
369 shared memory segment object currently in use.
370
371 sem
372
373 Called on either the tied variable or the tie object, returns the
374 semaphore object related to the memory segment currently in use.
375
376 attributes
377
378 Retrieves the list of attributes that drive the IPC::Shareable object.
379
380 Parameters:
381
382 $attribute
383
384 Optional, String: The name of the attribute. If sent in, we'll return
385 the value of this specific attribute. Returns undef if the attribute
386 isn't found.
387
388 Returns: A hash reference of all attributes if $attributes isn't sent
389 in, the value of the specific attribute if it is.
390
391 global_register
392
393 Returns a hash reference of hashes of all in-use shared memory segments
394 across all processes. The key is the memory segment ID, and the value
395 is the segment and semaphore objects.
396
397 process_register
398
399 Returns a hash reference of hashes of all in-use shared memory segments
400 created by the calling process. The key is the memory segment ID, and
401 the value is the segment and semaphore objects.
402
403LOCKING
404
405 IPC::Shareable provides methods to implement application-level advisory
406 locking of the shared data structures. These methods are called
407 shlock() and shunlock(). To use them you must first get the object
408 underlying the tied variable, either by saving the return value of the
409 original call to tie() or by using the built-in tied() function.
410
411 To lock and subsequently unlock a variable, do this:
412
413 my $knot = tie my %hash, 'IPC::Shareable', { %options };
414
415 $knot->lock;
416 $hash{a} = 'foo';
417 $knot->unlock;
418
419 or equivalently, if you've decided to throw away the return of tie():
420
421 tie my %hash, 'IPC::Shareable', { %options };
422
423 tied(%hash)->lock;
424 $hash{a} = 'foo';
425 tied(%hash)->unlock;
426
427 This will place an exclusive lock on the data of $scalar. You can also
428 get shared locks or attempt to get a lock without blocking.
429
430 IPC::Shareable makes the constants LOCK_EX, LOCK_SH, LOCK_UN, and
431 LOCK_NB exportable to your address space with the export tags :lock,
432 :flock, or :all. The values should be the same as the standard flock
433 option arguments.
434
435 if (tied(%hash)->lock(LOCK_SH|LOCK_NB)){
436 print "The value is $hash{a}\n";
437 tied(%hash)->unlock;
438 } else {
439 print "Another process has an exlusive lock.\n";
440 }
441
442 If no argument is provided to lock, it defaults to LOCK_EX.
443
444 There are some pitfalls regarding locking and signals about which you
445 should make yourself aware; these are discussed in "NOTES".
446
447 Note that in the background, we perform lock optimization when reading
448 and writing to the shared storage even if the advisory locks aren't
449 being used.
450
451 Using the advisory locks can speed up processes that are doing several
452 writes/ reads at the same time.
453
454REFERENCES
455
456 Although references can reside within a shared data structure, the tied
457 variable can not be a reference itself.
458
459DESTRUCTION
460
461 perl(1) will destroy the object underlying a tied variable when then
462 tied variable goes out of scope. Unfortunately for IPC::Shareable, this
463 may not be desirable: other processes may still need a handle on the
464 relevant shared memory segment.
465
466 IPC::Shareable therefore provides several options to control the timing
467 of removal of shared memory segments.
468
469 destroy Option
470
471 As described in "OPTIONS", specifying the destroy option when tie()ing
472 a variable coerces IPC::Shareable to remove the underlying shared
473 memory segment when the process calling tie() exits gracefully.
474
475 NOTE: The destruction is handled in an END block. Only those memory
476 segments that are tied to the current process will be removed.
477
478 remove
479
480 tied($var)->remove;
481
482 # or
483
484 $knot->remove;
485
486 Calling remove() on the object underlying a tie()d variable removes the
487 associated shared memory segments. The segment is removed irrespective
488 of whether it has the destroy option set or not and irrespective of
489 whether the calling process created the segment.
490
491 clean_up
492
493 IPC::Shareable->clean_up;
494
495 # or
496
497 tied($var)->clean_up;
498
499 # or
500
501 $knot->clean_up;
502
503 This is a class method that provokes IPC::Shareable to remove all
504 shared memory segments created by the process. Segments not created by
505 the calling process are not removed.
506
507 clean_up_all
508
509 IPC::Shareable->clean_up_all;
510
511 # or
512
513 tied($var)->clean_up_all;
514
515 # or
516
517 $knot->clean_up_all
518
519 This is a class method that provokes IPC::Shareable to remove all
520 shared memory segments encountered by the process. Segments are removed
521 even if they were not created by the calling process.
522
523RETURN VALUES
524
525 Calls to tie() that try to implement IPC::Shareable will return an
526 instance of IPC::Shareable on success, and undef otherwise.
527
528AUTHOR
529
530 Benjamin Sugars <bsugars@canoe.ca>
531
532MAINTAINED BY
533
534 Steve Bertrand <steveb@cpan.org>
535
536NOTES
537
538 Footnotes from the above sections
539
540 1. If the process has been smoked by an untrapped signal, the binding
541 will remain in shared memory. If you're cautious, you might try
542
543 $SIG{INT} = \&catch_int;
544 sub catch_int {
545 die;
546 }
547 ...
548 tie $variable, IPC::Shareable, { key => 'GLUE', create => 1, 'destroy' => 1 };
549
550 which will at least clean up after your user hits CTRL-C because
551 IPC::Shareable's END method will be called. Or, maybe you'd like to
552 leave the binding in shared memory, so subsequent process can recover
553 the data...
554
555 General Notes
556
557 o
558
559 When using lock() to lock a variable, be careful to guard against
560 signals. Under normal circumstances, IPC::Shareable's END method
561 unlocks any locked variables when the process exits. However, if an
562 untrapped signal is received while a process holds an exclusive lock,
563 DESTROY will not be called and the lock may be maintained even though
564 the process has exited. If this scares you, you might be better off
565 implementing your own locking methods.
566
567 One advantage of using flock on some known file instead of the
568 locking implemented with semaphores in IPC::Shareable is that when a
569 process dies, it automatically releases any locks. This only happens
570 with IPC::Shareable if the process dies gracefully.
571
572 The alternative is to attempt to account for every possible
573 calamitous ending for your process (robust signal handling in Perl is
574 a source of much debate, though it usually works just fine) or to
575 become familiar with your system's tools for removing shared memory
576 and semaphores. This concern should be balanced against the
577 significant performance improvements you can gain for larger data
578 structures by using the locking mechanism implemented in
579 IPC::Shareable.
580
581 o
582
583 There is a program called ipcs(1/8) (and ipcrm(1/8)) that is
584 available on at least Solaris and Linux that might be useful for
585 cleaning moribund shared memory segments or semaphore sets produced
586 by bugs in either IPC::Shareable or applications using it.
587
588 Examples:
589
590 # List all semaphores and memory segments in use on the system
591
592 ipcs -a
593
594 # List all memory segments and semaphores along with each one's associated process ID
595
596 ipcs -ap
597
598 # List just the shared memory segments
599
600 ipcs -m
601
602 # List the details of an individual memory segment
603
604 ipcs -i 12345678
605
606 # Remove *all* semaphores and memory segments
607
608 ipcrm -a
609
610 o
611
612 This version of IPC::Shareable does not understand the format of
613 shared memory segments created by versions prior to 0.60. If you try
614 to tie to such segments, you will get an error. The only work around
615 is to clear the shared memory segments and start with a fresh set.
616
617 o
618
619 Iterating over a hash causes a special optimization if you have not
620 obtained a lock (it is better to obtain a read (or write) lock before
621 iterating over a hash tied to IPC::Shareable, but we attempt this
622 optimization if you do not).
623
624 The fetch/thaw operation is performed when the first key is accessed.
625 Subsequent key and and value accesses are done without accessing
626 shared memory. Doing an assignment to the hash or fetching another
627 value between key accesses causes the hash to be replaced from shared
628 memory. The state of the iterator in this case is not defined by the
629 Perl documentation. Caveat Emptor.
630
631CREDITS
632
633 Thanks to all those with comments or bug fixes, especially
634
635 Maurice Aubrey <maurice@hevanet.com>
636 Stephane Bortzmeyer <bortzmeyer@pasteur.fr>
637 Doug MacEachern <dougm@telebusiness.co.nz>
638 Robert Emmery <roberte@netscape.com>
639 Mohammed J. Kabir <kabir@intevo.com>
640 Terry Ewing <terry@intevo.com>
641 Tim Fries <timf@dicecorp.com>
642 Joe Thomas <jthomas@women.com>
643 Paul Makepeace <Paul.Makepeace@realprogrammers.com>
644 Raphael Manfredi <Raphael_Manfredi@pobox.com>
645 Lee Lindley <Lee.Lindley@bigfoot.com>
646 Dave Rolsky <autarch@urth.org>
647 Steve Bertrand <steveb@cpan.org>
648
649SEE ALSO
650
651 perltie, Storable, shmget, ipcs, ipcrm and other SysV IPC manual pages.
652
653