The Perl fork function is an implementation of a concept in operating systems.
First, you need to understand that an OS's idea of a process is something like "a context in which a program runs". (OS people, bear with me; I'm just trying to get the idea across.) In other words, if I'm going to run many programs at the same time on the same hardware, I have to keep them from bumping into each other. That's the notion of a context; the operating system creates processes and assigns resources to them. For example, the operating system has to switch contexts so that all programs have a fair chance to run. From its point of view, it can do this by providing the CPU resource to a given process. (Meditate on this until your point of view changes. ;-)
OK, so how do I create these contexts or processes? One way is to give each process a way to create a new one. (Ignore for the moment how the first process was created. Divine intervention.) Now, a context isn't much good without something in it -- that is, a program to run. What should a newly created process be running? Well, how about just a duplicate of the calling program? That's the fork solution: it creates a duplicate (almost) of the calling program and sets both in motion.
OK, so that's the operating systems concept of a fork. What about Perl? So far, I've got just a system call which doesn't necessarily have to be called fork; it could be called, say, newproc. Now programming languages need a way to use it.
Perl provides fork() as a handle to that call, even if it's named something else in the underlying operating system. In other words, the Perl function fork() is part of the language, but is implemented different ways (or not at all!) on different operating systems. Its semantics are what I've outlined above: create a duplicate of the running program.
"Wait," I hear you say (monks can hear over the internet). "If I have two duplicate programs, how do I know which is which?" Actually, the newly created process isn't an exact duplicate of the calling program. The salient difference is the return code from fork. In the new process, fork returns zero; in the parent it returns non-zero (usually an identifying number for the new process). That's why you'll usually see:
if (fork() == 0) {
# code executed by child process
}
else {
# code executed by parent process
}
The crucial thing to realize is that two different program instances are executing the if after fork returns.
/me cuts it short because the boss is calling
HTH |