in Operating System edited by
3,070 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 ?

in Operating System edited by
by
3.1k views

2 Comments

One more example to illustrate $Copy\ on\ Write:$

$Child : x=2$

$Parent : x=0$




14
14
Nicely explained :)
0
0

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

4 Comments

Mam how come parent and child process can get Same physical address space because OS doesn't allow the physical address space to overlap between process unless explicitly we are using shared memory sort of thing.

Refer :-   https://gateoverflow.in/206872/fork-system-call          (The Chosen answer)

Please correct me :)

0
0

That answer is correct but incomplete. :)
Refer this for gaining more insight. 
 

1
1

Thanks @Soumya29 Mam :)

0
0

Related questions