How to get variables shared between child and parent process while using fork in perl

15,861

Solution 1

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.

Solution 2

This is case "1) child process gets separate instance of global variable declared in parent process".

The point of separate processes is to separate memory. So you can't share variables between the parent and the child process once the fork occured.

You should have a look to the perlipc manual page that list some other options for inter-process communication (IPC). And look at the other StackOverflow questions about parent-child communication.

Solution 3

Example of code:

my $ipckey = IPC_PRIVATE;
my $idshm = shmget( $ipckey, 200, 0666 ) || die "\nCreation shared memory failed $! \n";

shmread( $idshm, $xxx, 0, 1 ) || warn "\n\n shmread $! \n";

shmwrite( $idshm, $xxx , 0, 1 ) || warn "\n\n shmwrite $! \n";
Share:
15,861
chaitu
Author by

chaitu

software engineer working on bluetooth stack

Updated on June 05, 2022

Comments

  • chaitu
    chaitu almost 2 years

    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().