I know that processes do not share same context in python. But what about singleton objects? I was able to get the child process share same internal object as parent process, but am unable to understand how. Is there something wrong with the code below?
This could be a follow up to this stackoverflow question.
This is the code I have:
Singleton.py:
import os
class MetaSingleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(MetaSingleton, cls).__call__(*args, **kwargs)
return cls._instances[cls]
class Singleton:
__metaclass__ = MetaSingleton
def __init__(self):
self.key="KEY TEST"
print "inside init"
def getKey(self):
return self.key
def setKey(self,key1):
self.key = key1
process_singleton.py:
import os
from Singleton import Singleton
def callChildProc():
singleton = Singleton()
print ("singleton key: %s"%singleton.getKey())
def taskRun():
singleton = Singleton()
singleton.setKey("TEST2")
for i in range(1,10):
print ("In parent process, singleton key: %s" %singleton.getKey())
try:
pid = os.fork()
except OSError,e:
print("Could not create a child process: %s"%e)
if pid == 0:
print("In the child process that has the PID %d"%(os.getpid()))
callChildProc()
exit()
print("Back to the parent process")
taskRun()