in reply to Re: Re: Forking and loops: A plea for understanding.
in thread Forking and loops: A plea for understanding.

How can perl create a copy and then start executing in the middle of a a loop?

I've to explain this in Unix term. There's no fork() on Windows; it's emulated on that OS, but I've no desire to know how.

First, it's not a Perl thing, it's an OS thing. The Perl fork() just does some handy stuff for the programmer (like flushing buffers) and then calls the system's fork that does all the neat stuff. Second, to understand how fork works, you first have to understand a little what consists of a process.

A process occupies several parts of the memory. There's the text segment, which is where the (binary) program is stored, and there's the data segment which contains the variable data of a process. This is the part that changes during the lifetime of a process. (Lots of handwaving here, in reality most OSses have more segments, but that's not important now). There's also a program counter, a little pointer that's used to keep track where the process is in the execution of the program. For sake of the argument, consider the program counter to be in the data segment. Note that for the case of a Perl program, it's perl, the binary, that is in the text segment, and the (compiled) Perl program that's in the data segment - so the entire Perl program is copied.

Now, what happens at a fork? The OS creates a new process; the child. The child *shares* the text segment, but the data segment is copied. (The latter is usually implemented using copy-on-write, but that's just a technique to delay the copying, the program won't notice it). This includes the program counter! So, both the child and the parent continue at the same point in the program after a fork. Only the return value is different. Perl doesn't start executing in the middle of a loop - it was still there!

Note that the above was a simplied version of what really happens. What really happens will differ from Unix flavour to Unix flavour, but many of those details aren't noticeable for most programmers.

Abigail

  • Comment on Re: Forking and loops: A plea for understanding.