Siddharth Kamaria
Siddharth Kamaria

Reputation: 2717

Different outputs while forking process

I'm getting different number of outputs in the below attached code. Sometimes it prints 6 PID's or sometimes 8 PID's. Desired output is 7 PID's. Though sometimes I'm able to get 7 PID's.

Process tree:

          A
       /  |  \
      B   C   D
     / \  |
    E   F G

My Code:

#include <stdio.h>

void main()
{
    int pidb=-1;
    if(fork()==0) pidb=getpid();
    fork();
    if(getppid()!=pidb) fork(); 
    printf("%d\n",getpid());
}

Note: Assume that the fork call will be successful.

[update]

We need to achieve it using 3 fork calls.

Upvotes: 0

Views: 80

Answers (2)

Sourav Ghosh
Sourav Ghosh

Reputation: 134286

You forgot to include the required header files. to use fork(), you need to have

   #include <sys/types.h>
   #include <unistd.h>

With this, I'm able to get the expected output.

That said, in your code, it seems you don't wait for completion of child processes.

You need to have a wait() call in your parent process to wait till child has finished execution.

Also, it's not void main(), actually int main(void). a return 0 at the end is good practice.

Upvotes: 1

Jeegar Patel
Jeegar Patel

Reputation: 27210

#include <stdio.h>

    void main()
    {
        int pidb=-1;
        if(fork()==0) pidb=getpid();
        fork();
        if(getppid()!=pidb) fork();
        wait(NULL);  // Wait for all child process
        printf("%d\n",getpid());
    }

This is what you want. This will print 7 pid of those 7 process


Final process tree would be like this

          A (First fork) 
       /    \
      B      c   (2nd fork) 
     / \     / \
    D   E    F  G  (3rd fork)
   / \  / \  /\   | 
   1  2 3 4  5 6  7

Upvotes: 1

Related Questions