首页 > 技术文章 > 5.1.3 网络编程进阶---查看进程ID和父进程ID

beallaliu 2018-06-16 09:33 原文

获取本进程id: os.getpid() 

或: 

from multiprocessing import current_process
current_process().pid

获取父进程id:   os.getppid()

 

from multiprocessing import Process
import time
import os


class MyProcess(Process):    # 继承Process类
    def __init__(self, name):
        super().__init__()
        self.name = name

    def run(self):   # 必须重写run方法
        print('%s is running; 父进程id是:%s' % (os.getpid(), os.getppid()))
        time.sleep(3)
        print('%s is ending; 父进程id是:%s' % (os.getpid(), os.getppid()))


if __name__ == '__main__':
    p = MyProcess('xxx')
    p.start()     # start自动绑定到run方法
    print('主进程ID是:%s; 主进程的父进程ID是: %s' % (os.getpid(), os.getppid()))  # 主进程的父进程是pycharm或执行该脚本的进程


# 输出结果:
# 主进程ID是:771; 主进程的父进程ID是: 540
# 772 is running; 父进程id是:771
# 772 is ending; 父进程id是:771

 

推荐阅读