Search code examples
c++forkparent

Output window when using Fork


What is output of following code:

void ChildProcess(void); /* child process prototype */
void ParentProcess(void); /* parent process prototype */

int main(void)
{
 pid_t pid; //stores the process ID
 pid = fork(); //creates a child process of same program
 if (pid == 0)
 ChildProcess(); //If a child is executing a process,for it , PID will be 0
 else
 ParentProcess(); //The parent can have access to child process PID
return 0;
}



void ChildProcess(void)
{
 for(int i=0; i< 100; i++)
    cout<<"I am the child"<<endl;
}

void ParentProcess(void)
{
for(int i=0; i< 100; i++)
 cout<<"I am the father"<<endl;
}

Child process and his parent print output on same output console(Window)?! I mean output is like: I am the father I am the child I am the father I am the child I am the father I am the child


Solution

  • Yes they output to the same console, so you should get:

    I am the child
    I am the father
    I am the child
    I am the father
    I am the child
    I am the father
    I am the child
    I am the father
    ...
    

    But you can also have something like:

    I am the father
    I am the child
    I am the child
    I am the child
    I am the father
    I am the father
    ...
    

    The order is highly dependent on the operating system, the number of cores of the machine, and will probably be quite random.