Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if running current process is parent?

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()  
like image 557
kyrenia Avatar asked Feb 16 '17 19:02

kyrenia


People also ask

How do you know if a process is a parent?

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.

How do you know if a process is parent or child?

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.

How can we know that which is the parent process and child process if we are using fork ()?

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.

Do all processes have a parent?

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.


1 Answers

This will print out True if current process is the parent process.

from multiprocessing import current_process

print(current_process().name == 'MainProcess') 
like image 193
Dev Aggarwal Avatar answered Oct 23 '22 09:10

Dev Aggarwal