It creates a copy of the script and executes the copy.

That may be what's bothering you. The trick is that both the parent and child go on from the same point, that where fork is called. The child gets a private copy of all the parent's environment, stack, memory and everything. It is said that fork returns twice, once in the parent and once in the child. The return value of fork is the only difference between the two, besides the dynamical process table variables like $$.

Following the parent only, your server loop looks like

while(my $client = $server->accept()) { next; }
A child ignores the next line and goes on to do the client handling and exit. That ends the program as far as the child is concerned.

Two points which you may not need to be reminded of. The fork call can fail, returning undef, leaving you in the parent but executing child code. When you hit exit then, your server quits.

Second, you may be spinning out lots of zombies. In a persistent server, it is probably easiest to set $SIG{CHLD}='IGNORE'; if your OS supports that.

Parallel::ForkManager is a good wrapper for this sort of thing.

After Compline,
Zaxo


In reply to Re: Forking and loops: A plea for understanding. by Zaxo
in thread Forking and loops: A plea for understanding. by BUU

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.