user3754974
user3754974

Reputation: 279

Creating new processes

I am creating new processes by forking:

printf("original process = %d\n", getpid());
fork();
printf("parent = %d; child = %d\n", getpid(), getppid());
fork();
printf("parent = %d; child = %d\n", getpid(), getppid());
if(fork() == 0){
        printf("parent = %d; child = %d\n", getpid(), getppid());
        if(fork() == 0){
                    printf("parent = %d; child = %d\n", getpid(), getppid());
        }    
}
fork();
printf("parent = %d; child = %d\n", getpid(), getppid());

and I want to print out how many processes I have created. My approach as seen above is not the best way of printing how many processes have been created. So my question is: how can we print how many new processes have been created each time we fork without having some kind of loop?

Upvotes: 0

Views: 86

Answers (2)

Santosh A
Santosh A

Reputation: 5361

As each creates/spawns a child process,
Based on the order in which the fork() is called
Totally 24 child process are created, this is how its done

1st fork(); (has 4 more fork() calls)
2st fork(); (has 3 more fork() calls)
3st fork(); (has 2 more fork() calls)
4st fork(); (has 1 more fork() calls)

So the totall number of child process would be 4! - 1, that is 4x3x2x1 = 24 - 1
23 child process are created

Upvotes: 0

rodrigo
rodrigo

Reputation: 98516

Each successful call to fork creates a new process, and both the parent and the child return from fork(). The child will get 0 as return, the parent the PID of the child.

printf("I am the root %d\n", getpid());
if (fork() == 0)
    printf("I am %d, child of %d\n", getpid(), getppid());
if (fork() == 0)
{
    printf("I am %d, child of %d\n", getpid(), getppid());
    if (fork() == 0)
        printf("I am %d, child of %d\n", getpid(), getppid());
}
if (fork() == 0)
    printf("I am %d, child of %d\n", getpid(), getppid());

And so on...

The problem in your code is that you are printing the text in some cases without checking the return value of fork(), so these lines will be printed both by the parent and the child. With my code, each process prints just one line, on creation.

Upvotes: 1

Related Questions