> -----Original Message----- > From: zentara [mailto:[EMAIL PROTECTED]] > Sent: Wednesday, October 24, 2001 1:03 PM > To: [EMAIL PROTECTED] > Subject: strange fork (if - else)behavior > > ... > OK, I'm just learning, so I wanted to try this fork statement. > > #!/usr/bin/perl > > use warnings; > my $program = 'ls'; > my $pid = fork(); > die("Unable to fork: \l$!.\n") unless defined($pid); > if ($pid) { > print "$pid\n"; > } else { > exec($program); > } > > Now what is confusing me, is the if-else behavior. > When I run this program sometimes just the pid is > printed, then sometimes the pid AND the ls is printed. > The ls is never printed alone. > > What's happening in the if-else statement that is > allowing both to be executed? Is it just accidental > timing, that the pid disappears after printing, but > before the else statement is evaluated?
fork() is used to create processes. Immediately after the fork() call, there are now TWO processes running. The one who called fork() is known as the "parent". In the parent process, the return value from fork() is the process id of the newly-created process, called the "child" (or undef if the child couldn't be created). The child process never called fork(), but it "returns" from fork() and begins executing at that point. The return value from fork() in the child process is always zero. So the purpose of the if statement is to separate what the parent will do from what the child will do. if $pid is true (non-zero), then we must be the parent, so we take the first branch. If $pid is false (zero), then we must be the child, and we take the second branch, in this case calling exec(). So in this case, both branches of the if statement ARE executed, but not by the same process. Since the child process inherits the open file descriptors of the parent process, both processes are sending their output to the same place, and if both write output, the output will be intermingled. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]