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

Hello All,

I have one loop and in there i am forking and calling one function which is calling DB handle defined as global variable. Below is the code.

foreach my $hostname (@host) { my $thr = fork(); if($thr) { #parent push(@childsall, $thr); next; } else { connecttohost($hostname); } } foreach my $child_pid (@childsall) { my $tmp = waitpid($child_pid, 0); } sub connecttohost { my($hname) = @_; my $query = sprintf("SELECT * FROM $DbName WHERE ue_id='$hname'); my $hash_ref = $::dbh->selectrow_hashref($query); }

dbh is defined as global variable. Now my question is how to keep global variable values in case of fork?

thanks --girija

Replies are listed 'Best First'.
Re: how to use global vars after forking()
by Corion (Patriarch) on Oct 15, 2015 at 09:43 UTC

    Have you read about what DBI has to say about fork? Usually, I consider it better to connect to the database only after the call to fork, because that way you can be certain that the state of the database library is consistent with the outside world.

Re: how to use global vars after forking()
by nikosv (Deacon) on Oct 15, 2015 at 10:12 UTC
    on top of that using DBI with fork is pretty involved,see DBI, fork, and clone.,isn't that a fork-bomb!,although a finite one? (since it runs until the end of the foreach loop)
Re: how to use global vars after forking()
by shmem (Chancellor) on Oct 15, 2015 at 16:30 UTC

    To expand what nikosv wrote: yes, I know this is stripped down example code - but in the child branch, you MUST exit

    foreach my $hostname (@host) { my $thr = fork(); if($thr) { #parent push(@childsall, $thr); next; } else { connecttohost($hostname); exit; # <---- here } } foreach my $child_pid (@childsall) { my $tmp = waitpid($child_pid, 0); }

    because otherwise each child resumes the loop at its current state, spawning child processes which spawn child processes which spawn child processes which spawn child processes which spawn...

    perl -le'print map{pack c,($-++?1:13)+ord}split//,ESEL'
      yes I am exiting in child branch. I got the answer. I can use IPC shareable and it works fine