【Python】开启子进程并获取PID

方式一
# import time
# from multiprocessing import Process
#
#
# def task(name):
# print('%s is running ' % name)
# time.sleep(3)
# print('%s is done' % name)
#
#
# if __name__ == '__main__':
# p = Process(target=task, kwargs={'name': '子进程1'}) # 调用task 传入参数name
# p.start() # 仅仅给操作系统发送信号
#
# print('主')

方式二
import time,os
from multiprocessing import Process


class MyProcess(Process):
def __init__(self, name):
super(MyProcess, self).__init__()
self.name = name

def run(self): # 固定名字run, 会被start调用
print('child <%s> is running, parent is <%s>' % (os.getpid(), os.getppid()))
time.sleep(3)
print('child <%s> is done, parent is <%s>' % (os.getpid(), os.getppid()))


if __name__ == '__main__':
p = MyProcess('子进程')
p.start()
print('主进程<%s>, pycharm<%s>' % (os.getpid(), os.getppid()))
posted @ 2018-08-26 17:42  caya  阅读(3719)  评论(0编辑  收藏  举报