zoukankan      html  css  js  c++  java
  • 获取进程编号

    1、原因:目的是为了验证主进程和子进程的关系。通过获取进程编号可以得知某个子进程是由哪个主进程创建出来的。

    2、获取当前进程编号:os.getpid()

    3、获取父进程编号:os.getppid()

    4、获取当前进程名字:multiprocessing.current_process()

    5、杀死当前指定进程: os.kill(进程ID,9) 第二个参数9表示强制杀死进程

    一、获取主进程编号及名字

    from multiprocessing import Process,current_process
    from time import *
    import os
    
    
    def sing():
        for i in range(3):
            print('唱歌中....')
            sleep(0.2)
        # 获取子进程的编号及进程名
        print("sing的进程编号为: %s, 名字是: %s" % (os.getpid(),current_process()))
        print("sing的父进程编号为:%s" %  (os.getppid()))
    
    
    def dance():
        for i in range(3):
            print('跳舞中....')
            sleep(0.2)
        # 获取子进程的编号及进程名
        print("dance的进程编号为:%s,名字是:%s" %(os.getpid(),current_process()))
        print("dance的父进程编号为:%s" % (os.getppid()))
    
    
    # 获取主进程的编号及进程名
    print("主进程的编号为:%s,名字为:%s" % (os.getpid(),current_process()))
    
    # 创建子进程
    p1 = Process(target=sing)
    p2 = Process(target=dance)
    
    # 启动子进程
    p1.start()
    p2.start()
    View Code

    运行效果:

    二、强制杀死进程

    from multiprocessing import Process,current_process
    from time import *
    import os
    
    
    def sing():
        for i in range(3):
            print('唱歌中....')
            sleep(0.2)
            os.kill(os.getpid(),9)
        # 获取子进程的编号及进程名
        print("sing的进程编号为: %s, 名字是: %s" % (os.getpid(),current_process()))
        print("sing的父进程编号为:%s" %  (os.getppid()))
    
    
    def dance():
        for i in range(3):
            print('跳舞中....')
            sleep(0.2)
        # 获取子进程的编号及进程名
        print("dance的进程编号为:%s,名字是:%s" %(os.getpid(),current_process()))
        print("dance的父进程编号为:%s" % (os.getppid()))
    
    
    # 获取主进程的编号及进程名
    print("主进程的编号为:%s,名字为:%s" % (os.getpid(),current_process()))
    
    # 创建子进程
    p1 = Process(target=sing)
    p2 = Process(target=dance)
    
    # 启动子进程
    p1.start()
    p2.start()
    View Code

    运行结果:

  • 相关阅读:
    海驾学车过程全揭秘——第六篇:辛苦的学车全过程
    择偶
    海驾学车过程全揭秘——第八篇:科目二集训及考试
    海驾学车过程全揭秘——第四篇:正式练车第一段
    痛苦的相对论
    不犹豫不后悔
    海驾学车过程全揭秘——第十篇:领驾照、办牡丹卡、陪练
    海驾学车过程全揭秘——第五篇:网上约车(电话约车)
    海驾学车过程全揭秘——第一篇:总述
    海驾学车过程全揭秘——第九篇:科目三集训及考试
  • 原文地址:https://www.cnblogs.com/yujiemeigui/p/14298277.html
Copyright © 2011-2022 走看看