How can I have a child process call a function in its parent process?
I'm writing a python program in which I need a child process (launched with the multiprocessing module) to call a function in its parent process.
Consider the following program that simply calls a function child_or_parent()
twice: first it calls child_or_parent()
in the parent process, and then it calls child_or_parent()
in a child process.
#!/usr/bin/env python3
import multiprocessing, os
# store the pid of our main (parent) process
parent_pid = os.getpid()
# simple function that tells you if it's the parent process or a child process
def child_or_parent():
if os.getpid() == parent_pid:
print( "I am the parent process" )
else:
print( "I am a child process" )
# first the parent process
child_or_parent()
# now a child process
child = multiprocessing.Process( target=child_or_parent )
child.start()
When executed, the above program outputs the following
I am the parent process
I am a child process
I would like to modify this program such that the child process calls the parent processes' child_or_parent()
function, and it outputs I am the parent process
.
The following program has a function named child_call_parent()
that contains pseudocode. What should I put there so that the child_call_parent()
function will actually execute the child_or_parent()
function inside the parent process?
#!/usr/bin/env python3
import multiprocessing, os
# store the pid of our main (parent) process
parent_pid = os.getpid()
# simple function that tells you if it's the parent process or a child process
def child_or_parent():
if os.getpid() == parent_pid:
print( "I am the parent process" )
else:
print( "I am a child process" )
def child_call_parent():
# FIXME this does not work!
self.parent.child_or_parent()
# have a child call a function in its parent process
child = multiprocessing.Process( target=child_call_parent )
child.start()