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().
Answer: Only the shared memory segments are shared between the parent process and the newly forked child process. Copies of the stack and the heap are made for the newly created process.
No, they are not shared in any way which is visible to the programmer; the processes can modify their own copies of the variables independently and they will change without any noticable effect on the other process(es) which are fork() parents, siblings or descendents.
Fork() creates a new context based on the context of the calling process. The fork() call is unusual in that it returns twice: It returns in both the process calling fork() and in the newly created process. The child process returns zero and the parent process returns a number greater then zero.
The named pipe, which could be one-way or duplex (two-way) can offer both reading and writing services for the processes. To send data from the parent process to the child process, the parent process creates the pipe file using the pipe name, then writes the data onto the pipe file.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With