2

In python3.6 I have the following code which forks a process, and the child changes a variable. However, the variable of the same name remains unchanged

import os, sys, time

var = 42

child_pid = os.fork()
if child_pid == 0:
    print(f"Child Process start {os.getpid()}.")
    var = 20
    print(f"Child variable {var}")
    time.sleep(10)
    print(f"Child Process end {os.getpid()}.")
    sys.exit(0)
else:
    print(f"Parent Process start {os.getpid()}.")
    for x in range(20):
       time.sleep(2)
       print(f"Parent variable {var}")
    print(f"Parent Process end {os.getpid()}.")

How can I share the variable var in the example between the child and parent process?

Alex
  • 41,580
  • 88
  • 260
  • 469

1 Answers1

1

Forking a process creates a new process with a new PID and in a separate memory space. So basically you can not share variables even if they are globals.

If you create a thread you could share global variables.

Otherwise with two (or more) processes you can use IPC (stands for Inter Process Communication) : https://docs.python.org/fr/3.5/library/ipc.html.

Common IPC are sockets (even local) but you can choose another one (e.g. memory mapping, message queues, shared memory ...).

Here is a post for the same problem but in C, the IPC being handled by the OS the principle remains the same : How to share memory between process fork()?.

Dali
  • 344
  • 1
  • 10