0

This is the program I wrote

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<iostream>
#include<wait.h>
int main(void){
    std::cout << "My process " << getpid() << std::endl;
    int i;
    for(i=0;i<2;i++){
        int j = fork();
        wait(NULL);

        std::cout << "Process id :" << getpid() <<" and parent:"<< getppid()<< " and value returned is " << j <<std::endl;
    }
    return 0;
}

This is the output I get :

My process 5501
Process id :5502 and parent:5501 and value returned is 0
Process id :5503 and parent:5502 and value returned is 0
Process id :5502 and parent:5501 and value returned is 5503
Process id :5501 and parent:2828 and value returned is 5502
Process id :5504 and parent:5501 and value returned is 0
Process id :5501 and parent:2828 and value returned is 5504

Could someone explain the output to me? The intention of the program was that processes would be "visited" in a DFS manner. However, I'm not understanding how the value returned is 5503 in the third line and also why, even though I'm running the loop only twice, is 5504 being created? Thanks in advance.

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
Amit Rege
  • 37
  • 4

1 Answers1

0

5503 is being returned to the parent that called fork(), because in a parent, fork() returns the PID of it's newly-created child, and in the child, 0 is returned. So you need to do an if on the return value from fork() to test whether you are in the parent or child so you can run the subsequent code in only the one you want, otherwise it will be ran in both.

As for the second part of your question, you need to check if you are in the parent (or child, depending on who you want to create the second child) before forking (and waiting--only wait a parent) again (the second iteration of the for loop); if you don't, both the parent and child (from the first time it's called in the first iteration) will call fork() and each create another child. That is why the parent is creating 5504.

RastaJedi
  • 641
  • 1
  • 6
  • 18
  • The checks are intentionally not present. I realized my mistake. I got confused and forgot to keep track of the original parent process of each fork. Thanks for the help anyway. – Amit Rege Aug 29 '16 at 16:53