O'Reilly logo

Perl Cookbook by Nathan Torkington, Tom Christiansen

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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++; ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required