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

When you call fork, does the newly minted child process start from the same line number the parent was on when it forked, or does it take it from the top? My children seem to be running code meant for the parent... ltg

Replies are listed 'Best First'.
Re: fork question
by suaveant (Parson) on Apr 11, 2001 at 23:16 UTC
    Starts right from the fork, that's why you often see...
    if(fork()) { #parent } else { #child }
    fork returns 0 in the child, the pid of the child to the parent, and goes from there
                    - Ant
      With just the if (fork) this or that, it's really clear. What I have is

      print LOG "Files and statuses" bunch of logic to figure out command if (fork()) { update a hash } else { go do the command exit }

      And my raft of print statements shows that the print command is getting issued multiple times. Can't figure out how it's getting called. I can't seem to find any examples that have a bunch of stuff above the fork to see if I'm missing anything.

        I don't know if it would make a difference, but your print LOG line has no ; at the end of the line

        Here's what might be happening... you don't print a \n and unless you have autoflush on maybe the parent and child are both flushing to the log...
                        - Ant

Re: fork question
by traveler (Parson) on Apr 11, 2001 at 23:25 UTC
    The first two replies are (clearly) correct, but if you are executing parent code in the child, it might be that you do not exit in the child. In that case the child may continue with parent code.

    traveler

Re: fork question
by astanley (Beadle) on Apr 11, 2001 at 23:20 UTC
    If you want to see whether you're in the parent or the child do something like this:
    while ($pid = fork()) { if ($pid) { print "$pid\n"; #returns nonzero in the parent } else { print "$pid\n"; #returns zero in the child } }
    -Adam Stanley
    Nethosters, Inc.
      Umm, I just though it should be pointed out that your code exits the while loop if it is the child, and loops forever spawning off children like bionic rabbits if it is the parent... at least, it looks it. Child returns 0, so while loop fails, parent gets pid, enters loop, prints pid, forks again, ad nauseum
                      - Ant
(jptxs) Re: fork question
by jptxs (Curate) on Apr 12, 2001 at 06:02 UTC
    I have been starting to use fork a lot lately and found the fork page in Camel 3(pg 715) to be indispensable. It is a short coherent example with just enough explanation. good luck =)
    "A man's maturity -- consists in having found again the seriousness one had as a child, at play." --Nietzsche