Pregunta

Here's a program with fork and waitpid.

#!/usr/bin/perl
use strict;
use warnings;
my ($childProcessID, $i);

print "I AM THE ONLY PROCESS.\n";

$childProcessID = fork ();

if ($childProcessID){
        print "I am the parent process.\n";
        print "I spawned a new process with ID $childProcessID\n";
        waitpid ($childProcessID, 0);
        print "The child process is terminated with status $?\n";
    }
else{
    for ($i = 0; $i <= 10; $i++){
         print "I am the child process: Counting $i\n";
    }
}

The output may look like the following.

I AM THE ONLY PROCESS.
I am the parent process.
I spawned a new process with ID 7610
I am the child process: Counting 0
I am the child process: Counting 1
I am the child process: Counting 2
I am the child process: Counting 3
I am the child process: Counting 4
I am the child process: Counting 5
I am the child process: Counting 6
I am the child process: Counting 7
I am the child process: Counting 8
I am the child process: Counting 9
I am the child process: Counting 10
The child process is terminated with status 0

Now with many similar programs regarding fork on web and in books, that says

Code in if block is executed by parent process, while that in else is executed by child process. And waitpid is used to wait for childs to finish.

My question is

How and why is else block executed for child process? I get that fork has created new child process. But how execution for child (that is else block) happens after fork statement? Can somebody explain me this step by step for child process or maybe more insight into something that I am missing like why child doesn't execute statement below?

print "I AM THE ONLY PROCESS.\n";
¿Fue útil?

Solución

Fork splits the current process into two when it is executed. Both processes continue executing right after the fork call.

The only* difference between the two resulting processes is that in one (the parent), fork() returns the child's PID, while in the other (the child), fork() returns zero.

So in the parent, the $childProcessID is non-zero and the if branch is taken, while in the child that variable is zero and the else branch is executed.

* Probable not really pedantically true.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top