edited by
3,947 views
5 votes
5 votes
#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>

void forkexample() {

    int x = 1;

    if (fork() == 0)

        printf("Child has x = %d\n", ++x);

    else

        printf("Parent has x = %d\n", --x);

}

int main()

{

    forkexample();

    return 0;

}

 What will be the output?

Parent has x = 0
Child has x = 2
     (or)
Child has x = 2
Parent has x = 0

I guess both because we dont know who will return first parent or child is it ?

edited by

1 Answer

11 votes
11 votes

Parent and child processes share the physical address space as long as both the processes are just reading from there.
When the first one will try to write there, the data from physical address will be copied to a new physical address.

In this question, it doesn't matter which process will execute first.
When $1^{st}$ write took place, they will have different copies of data. 

Fork() returns 0 to the child process, so in child process 2 will get printed.
Fork() returns $Pid$ of child process to parent process, so in parent process 0 will get printed.
 

edited by

Related questions

1 votes
1 votes
2 answers
2
junaid ahmad asked Jan 1, 2019
1,455 views
int main(void) { int var1=100; int pid; if(pid==fork()) var1=200; fork(); printf("%d",var1); return 0; }what could be the output ?a)100 100 200 200b)200 200 200 200c)none...
1 votes
1 votes
1 answer
3
2 votes
2 votes
3 answers
4
Philosophical_Virus asked Dec 10, 2023
767 views
Int main (){fork();printf("a");fork();printf("b");return 0;}How many distinct outputs are possible of above code? And also give outputs