python获取进程编号


使用os模块获取进程编号

# 导包
import multiprocessing
import time
import os

def dance():
    print('跳舞子进程编号', os.getpid())
    print('跳舞的父进程编号', os.getppid())
    for i in range(3):
        print('跳舞中...')
        time.sleep(0.2)

def sing():
    print('唱歌子进程编号', os.getpid())
    print('唱歌的父进程编号', os.getppid())
    for i in range(3):
        print('唱歌中...')
        time.sleep(0.2)

# 创建子进程
# Process(group=,target=,name=,args=,kwargs=)
# group进程组,目前只能使用None,一般不设置
# target 进程执行的目标
# name 进程名 默认为process-1 ...慢慢递增
# args 不定长参数,元组传入
# kwargs 不定长参数,字典传入

dance_process = multiprocessing.Process(target=dance)
sing_process = multiprocessing.Process(target=sing)

# print(multiprocessing.current_process) 当前进程


# 执行进程
if __name__ == '__main__':
    # 获取进程编号 os.getpid 在主进程中获取的就是主进程编号,子进程就是子进程的编号
    # os.getppid 获取父进程编号
    print('主进程编号', os.getpid())
    sing_process.start()
    dance_process.start()


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM