Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hello Monks, I seek your divine wisdom in solving or helping me solve a problem with keeping data persistant while using Net::Daemon in fork mode. When I run the script in single mode the stored data remains between sessions but when I run the script using fork mode the stored data is lost with each new session. What do I need to do to be able to retain the data while running in fork mode ?

Hope I made some sense.. Thanks !!
#/usr/bin/perl use strict; use test_demon; require Net::Daemon; my(%PERSISTANT_HASH); my $server = test_demon->new( { 'pidfile' => 'test_demon.pid', 'logfile' => 'test_demon.log', 'localport' => 81, 'mode' => 'fork'}, \@ARGV); $server->Bind(); package test_demon; use strict; use vars qw($VERSION @ISA); @ISA = qw(Net::Daemon); sub Run ($) { my($self) = @_; my($line, $sock); $sock = $self->{'socket'}; while (1) { if (!defined($line = $sock->getline())) { if ($sock->error()) { $self->Error("Client error %s",$sock->error() ); }; $sock->close(); return; }; $line=~s/\r|\n//gi; my ($command,$key,$value) = split(/ /,$line,3); $command = lc($command); if ($command eq "set") { $::PERSISTANT_HASH{$key} = $value; }; if ($command eq "bye") { $sock->close(); return; } else { print $sock $::PERSISTANT_HASH{$key} . "\n"; }; }; $sock->close(); }; 1;

Replies are listed 'Best First'.
Re: Persistant data using Net::Daemon in fork mode
by wog (Curate) on Jul 14, 2001 at 05:35 UTC
    That data won't be shared after forking is to be expected; forking creates a whole new process that is completely seperate from the old one (on UNIX-like platforms, this is simulated on Windows, see perldoc perlfork.)

    If you want to share data between the processes, you can look to the IPC::Shareable or IPC::ShareLite modules though I don't know think they'd work on windows. You could also try a "real" database, or some DBM file that you would lock for every read and write.

    Note that $::PRESISTENT_HASH is not the hash created with my %PRESISTENT_HASH. The my statement creates a lexically scoped (to the file the my is in, in this case) variable, not a global variable, which is what %::PRESISTENT_HASH is.