Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Working of fork()

Tags:

c

linux

fork

I recently learned about the function fork() in C. Since this function creates two concurrent processes and these two processes share the memory. So I have the following code:

#include<stdio.h>
int main()
{
  int pid,i;
  i=0;
  pid=fork();
  if(pid==0)
    {
      i++;
      printf("child process:: address of i:%u value of i:%d\n",(int)&i,i);
    }
  else if(pid>0)
    {
      wait(NULL);
      i--;
      printf("parent process:: address of i:%u value of i:%d\n",(int)&i,i);
    }

  return 0;
}

The output I am getting is:

    child process:: address of i:3215563096 value of i:1
    parent process:: address of i:3215563096 value of i:-1

but since every time child is executing first so the value at memory location 3215563096 should become +1 which is on contrast 0 for the parent process.

My expected output is:

    child process:: address of i:3215563096 value of i:1
    parent process:: address of i:3215563096 value of i:0

Can someone please tell me where I am wrong?

like image 319
Piyush Goyal Avatar asked Jan 26 '26 12:01

Piyush Goyal


1 Answers

The second process does use the same memory as the original when using fork; however, the memory is marked as copy-on-write which means that as soon as the child tries to modify it the memory management in the OS will make a copy of the page so the original process will not see the modified memory. See more at fork wiki.

like image 133
Roger Lindsjö Avatar answered Jan 29 '26 01:01

Roger Lindsjö



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!