http://www.perlmonks.org?node_id=1004442


in reply to Global Variables Not Updated in Child Process

You seem to have a problem understanding the concept behind fork(). fork creates an exact copy of the current process, assigns it a new process ID, and makes both processes run independantly. Some things are shared, like file handles, but most (like memory) are not. (Actually, modern operating systems initially share most memory of both processes and use a copy-on-write mechanism to avoid expensive copy operations as long as possible.)

What you expect here is that your child will also have a hangover after only you got drunk.

Alexander

--
Today I will gladly share my knowledge and experience, for there are no sweeter words than "I told you so". ;-)

Replies are listed 'Best First'.
Re^2: Global Variables Not Updated in Child Process
by anshumangoyal (Scribe) on Nov 19, 2012 at 11:56 UTC
    So, is there anything I can use instead of forking? I want to run some processes in parallel and capture the results from them. My Prime focus is not forking but process some thing in a child process and get the values updated in parent.
      My Prime focus is not forking but process some thing in a child process and get the values updated in parent.

      So you want your son to learn French and your daugther to learn German, and you expect that you automatically speak both French and German as soon as both have finished learning. Does that work in real life? Nope. And it also won't work with fork()ed processes.

      Please read fork-exec, fork, and perhaps also exec.

      Generally, processes can't update other processes data. You need some kind of inter-process communication, or shared memory. Shared memory won't work well with Perl, because perl tends to move data around when its size changes. See perlipc for details on both ways.

      Another option, with its own set of traps, is using threads. Threads give you lightweight "processes" inside a single process, and threads can actually share variables. See perlthrtut for details. Of course, this works only if all external programs you are using now are merged into a single big program (possibly by moving each program into a single module).

      Alexander

      --
      Today I will gladly share my knowledge and experience, for there are no sweeter words than "I told you so". ;-)
        Dear afoken, the natural analogy is the parent process getting pregnant because the child process had sax