[Chicago-talk] Using Storable to exchange data between 2 processes

Steven Lembark lembark at wrkhors.com
Sat Jan 24 13:10:44 CST 2004



-- Jay Strauss <me at heyjay.com>

> this seems to work fine, and its much more speedy than the real life
> process.  And, it prevents a race condition
>
> Jay
>
># !/usr/bin/perl
> use strict;
> use Storable qw( freeze thaw );
> use IPC::ShareLite;
>
> my $share = new IPC::ShareLite( -key     => 1971,
>                              -create  => 'yes',
>                              -destroy => 'no' ) or die $!;
>
>
>
> if (my $pid = fork) {
>         parent();
> }
> else {
>         child();
> }
>
> sub parent {
>         my $data;
>
>         while (1) {
>                 sleep 1;
>                 $data = thaw( $share->fetch );
>                 print $data->{IBM}{last},"\n";
>         }
>
> }
>
> sub child {
>         my $data = {};
>
>         foreach (0..10000000) {
>                 $data->{IBM}{last} = $_;
>                 $share->store( freeze($data) );
>         }
> }

You might want to check for undef back from the
fork, or you'll run the child by itself when you
can't:

	if( (my $pid = fork) > 0 )
	{
	}
	elseif( defined $pid )
	{
	}
	else
	{
		die "Phorkatosis: $!";
	}

If you're really worried about speed, for(;;) with
an internal break should be faster than while(1),
which has to examine its loop variable at each
iteration (unless that's also changed in 5.8). The
for(;;) construct is the most common way of doing this
in C -- it's also easy to search for via /;;/, looking
for /1/ or /(1)/ in your editor are likely to turn up
extraneous statements.

--
Steven Lembark                               2930 W. Palmer
Workhorse Computing                       Chicago, IL 60647
                                            +1 888 359 3508



More information about the Chicago-talk mailing list