Sharing Variables in Different Processes
Problem
You want to share variables across forks or between unrelated processes.
Solution
Use SysV IPC, if your operating system supports it.
Discussion
While SysV IPC (shared memory, semaphores, etc.) isn’t as
widely used as pipes, named pipes, and sockets for interprocess
communication, it still has some interesting properties. Normally,
however, you can’t expect to use shared memory via
shmget
or the mmap
(2) system
call to share a variable among several processes. That’s
because Perl would reallocate your string when you weren’t
wanting it to.
The CPAN module
IPC::Shareable takes care of that. Using a clever
tie
module, SysV shared memory, and the Storable
module from CPAN allows data structures of arbitrary complexity to be
shared among cooperating processes on the same machine. These
processes don’t even have to be related to each other.
Example 16.11 is a simple demonstration of the module.
Example 16-11. sharetest
#!/usr/bin/perl # sharetest - test shared variables across forks use IPC::Shareable; $handle = tie $buffer, 'IPC::Shareable', undef, { destroy => 1 }; $SIG{INT} = sub { die "$$ dying\n" }; for (1 .. 10) { unless ($child = fork) { # i'm the child die "cannot fork: $!" unless defined $child; squabble(); exit; } push @kids, $child; # in case we care about their pids } while (1) { print "Buffer is $buffer\n"; sleep 1; } die "Not reached"; sub squabble { my $i = 0; while (1) { next if $buffer =~ /^$$\b/o; $handle->shlock(); $i++; ...
Get Perl Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.