如何确定运行当前进程是否为父进程?

时间:2017-02-16 19:47:04

标签: python multithreading python-3.x

如何从python中的多处理模块中确定当前进程是父进程还是子进程,来自导入的模块?

具体来说,我在导入的模块中有一些代码行,只需要运行一次 - 当代码首次运行时(即,不会在子进程启动时运行,并导入该模块)。

在主模块中,我能够使用if __name__ == '__main__':实现此目的,但这在导入的模块中不起作用。

如果相关,当前代码包括:

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()  

3 个答案:

答案 0 :(得分:2)

如果当前进程是父进程,则会打印出True

from multiprocessing import current_process

print(current_process().name == 'MainProcess') 

答案 1 :(得分:0)

如果我错了,请纠正我。根据我的理解,您想知道哪个进程(主进程或子进程)正在运行。您可以使用logging以指定%(processName)s %(threadName)s

的格式实现此目的
import multiprocessing
import logging
import sys
logger = logging.getLogger("mylogger")

formatter = logging.Formatter('%(processName)s %(threadName)s [%(levelname)s] %(message)s')

handler = logging.StreamHandler(stream=sys.stdout)
handler.setFormatter(formatter)
handler.setLevel(logging.DEBUG)

logger.addHandler(handler)
logger.setLevel(logging.DEBUG)

def f(x):
    logger.info(multiprocessing.current_process())
    return x * x

if __name__ == "__main__":
    logger.info("get started")
    p = multiprocessing.Pool()
    p.map(f, range(6))
    logger.info("done")

输出:

MainProcess MainThread [INFO] get started
ForkPoolWorker-1 MainThread [INFO] <ForkProcess(ForkPoolWorker-1, started daemon)>
ForkPoolWorker-2 MainThread [INFO] <ForkProcess(ForkPoolWorker-2, started daemon)>
ForkPoolWorker-3 MainThread [INFO] <ForkProcess(ForkPoolWorker-3, started daemon)>
ForkPoolWorker-1 MainThread [INFO] <ForkProcess(ForkPoolWorker-1, started daemon)>
ForkPoolWorker-4 MainThread [INFO] <ForkProcess(ForkPoolWorker-4, started daemon)>
ForkPoolWorker-2 MainThread [INFO] <ForkProcess(ForkPoolWorker-2, started daemon)>
MainProcess MainThread [INFO] done

答案 2 :(得分:0)

linux中的每个进程除了进程0(swapper)之外,每个进程都有一个父进程和可能有多个子进程(https://en.wikipedia.org/wiki/Parent_process)所以你的主线程也有一个父进程

这就是为什么你,如果你启动你的程序,必须存储从os分配给它的PID,因为它是你所有子进程的父(或祖父母,...)。

import os

parent_pid = os.getpid()
print "[parent] starts PID: %d" % (parent_pid, ) 

当你在一个孩子中时可以使用os.getppid()获取父进程,以获取当前进程的PID os.getpid()

from multiprocessing import Process
import os

def info(title):
    print(title)
    print('module name:', __name__)
    print('parent process:', os.getppid())
    print('process id:', os.getpid())

https://docs.python.org/3/library/multiprocessing.html

https://docs.python.org/2/library/os.html

http://www.programcreek.com/python/example/4464/os.getppid http://nullege.com/codes/search/os.getppid