Well fork is not only a perl command, but an unix command too.
What does fork do ?
It creates a copy of the actual running process. That's all!

What is this good for ?
Imagine you want to do several things at one time.
For example to count forward from 1 to 10 and at the same time backward from 10 to 1.
So you start like this:

for ($i=1;$i<=10;$i++) { print "$i\n" }; for ($j=10;$j>=1;$j--) { print "$j\n" }; # This will give you: 1 2 3 4 5 6 7 8 9 10 10 9 8 7 6 5 4 3 2 1
OK this is done one after the other in one process

To do it at the same time you can use fork:

$pid = fork(); if (! $pid) { ### This is the new process for ($j=10;$j>=0;$j--) { print "$j\n" }; } else { ### This is the parent process for ($i=1;$i<=10;$i++) { print "$i\n" }; }

What ??

Well with  $pid = fork() you create the same process again. This get's a new process-id and runs from the same point, where the fork was being done. The only difference between the parent and the child is, that only in the parent process the $pid variable is filled with the processnumber of the child process. So you can differ between the parent process ($pid=child-pid) and his child ($pid=empty).

Now you can do whatever you want in the if (! $pid) part.
It's important that all the vars declared and filled before the fork from the parent process are also available in the child process, but they are not visible in the other process!

Hope this makes it a bit more clearer, but I'm not sure :-)

----------------------------------- --the good, the bad and the physi-- -----------------------------------

In reply to Re: Forking hell by physi
in thread Forking hell by peschkaj

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.