Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does fork() create a duplicate instance of all the variables and object created by the parent process for the child process?

Suppose I have a main process running and in its execution it has initialized some pointers and created some instances of a predefined structure.

Now if I fork this main process, is seperate memory allocated for the pointers?And are duplicate instances of the previously existing variables, data structures created for this new process?

As an example of my requirement consider -

struct CKT
{
  ...
}

main()
{
   ...Some computations with the structure and other pointers.....
   pid_t pid = fork();
   if(pid == 0) //child
   {
       ..some more computations with the structure...but I need a 
       ..separate instance of it with all the pointers in it as well..
   }
   else if(pid > 0) // parent
   {
       ..working with the original instance of the structure..
   }
   // merging the child process with the parent...
   // after reading the data of the child processes structure's data... 
   // and considering a few cases...
}

Can anyone explain how do I achieve this??

like image 932
yashdosi Avatar asked Sep 13 '25 10:09

yashdosi


2 Answers

Yes, theorically, the fork system call will duplicate, among other, the stack of the parent. In pratical, otherwise, there is a common method, named copy-on-write, used in that case.

It consists on copy a given parent's memory page only when the child's process is trying to modify this memory space. It allows to reduce the cost of the fork system call.

The one thing which is not copy is the return value of fork: 0 in the child, and the PID of the child in the father.

like image 140
md5 Avatar answered Sep 14 '25 22:09

md5


Yes. It might not copy the memory space of the old process immediately, though. The OS will use copy-on-write where possible, copying each memory page the first time it is modified in either process.

COW is what makes one common use of fork (shortly followed by an exec in the child) efficient. The child process never actually uses most of the memory space inherited from the parent.

The copies in the new process will have exactly the same numeric addresses as they did in the old process, so all the pointers from the old process remain valid in the new process and point to the new process's objects. That's part of the point of virtual memory, it allows different process to refer to different physical memory using the same pointer value.

like image 28
Steve Jessop Avatar answered Sep 15 '25 00:09

Steve Jessop