I am using fork in my code. Before fork call in my code, the parent process has a global variable declared. So after the fork call does child process get a separate copy of the global variable on its own thread stack or shares the existing parent instance of global variable. so i guess there are three possibilities here 1) child process gets separate instance of global variable declared in parent process 2) child process shares the global variable with parent thread. (which is possibly not true) 3) child process doesnt have any sought of information about the global variable in parent thread
If either 2 or 3 options are true, i want to know if there is any way of getting the global variable and its "state/value at time of execution of fork()" declared in parent thread, in child process.
so broadly, is there any way of accessing parent processes variable and there states in child process created using fork().
Each process has its own memory space. A process can't normally access another process's memory.
In the case of fork
, the child process's memory space starts as an exact copy of the parents. That includes variables, code, etc. Changing any of these in one will not change any similar variable in the other.
So it's answer #1.
Even if you could, the question you should be asking isn't "how do I share variable?" but "how do I exchange data?". Having a controlled channel is less error-prone as it provides looser coupling and less action-at-a-distance.
Pipes are often use to communicate between parent and child, but there are many other options.