How is it possible to determine from the multiprocessing module in python if the current process is the parent or the child, from within imported modules?
Specifically, I have some lines of code in modules that i am importing, that only want running once - when the code is first run (i.e. not run ever time that a sub-process starts, and imports that module).
In the main module, i was able to achieve this using if __name__ == '__main__':
, however this does not work in imported modules.
In case of relevant, current code includes:
import multiprocessing as mp
pool = mp.Pool(processes=7, maxtasksperchild=1)
all_items = [pool.apply_async(sub_process, args=(value,) for value in all_values]
for item in all_items:
item.get()
To determine the parent process of a specific process, we use the ps command. The output only contain the parent process ID itself. Using the output from the ps command we can determine the name of the process.
Type the simply “pstree” command with the “-p” option in the terminal to check how it displays all running parent processes along with their child processes and respective PIDs. It shows the parent ID along with the child processes IDs.
if a call to fork() returns 0 it means that it is the child process that called the fork(). While if the return value of fork() is a positive integer, it means that the fork() was executed in the parent process and the returned positive integer is a PID of the child process.
Every process (except process 0) has one parent process, but can have many child processes. The operating system kernel identifies each process by its process identifier.
This will print out True
if current process is the parent process.
from multiprocessing import current_process
print(current_process().name == 'MainProcess')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With