进程可以通过调用multiprocessing的Process进行创建,下面代码创建两个进程。
[root@localhost ~]# cat twoproces.py
#!/usr/bin/env Python
from multiprocessing import Process
import os
def output():
print "My pid is :%d\n" % os.getpid()
print "My parent is:%d\n" % os.getppid()
def main():
p=Process(target=output)
p.start()
print "I am parent %d\n" % os.getpid()
if __name__=="__main__":
main()
运行结果如下:
[root@localhost ~]# ./twoproces.py
I am parent 7656
My pid is :7660
My parent is:7656
以下程序结果的mypid值将在两个进程中固定不变.
[root@localhost ~]# cat badprocessID.py
#!/usr/bin/env python
from multiprocessing import Process
import os
def output(mypid):
print "I am child %d ID :%d\n" % (os.getpid(),mypid)
def main():
mypid=os.getpid()
p=Process(target=output,args=(mypid,))
print "I am parent %d\n" % os.getpid()
p.start()
if __name__=="__main__":
main()
有与子进程并没有重设mypid,所以运行过程中mypid并没有任何改变。
下面代码将创建一个由子进程创建子进程的进程链。
[root@localhost ~]# cat simplechina.py
#!/usr/bin/env python
import os
from multiprocessing import Process
def output(howmany,childpid):
info = (howmany,os.getpid(),os.getppid(),childpid)
print "i:%d process ID:%d parent ID%d child ID %d\n" % info
def chain(howmany):
howmany = howmany-1
if howmany > 0:
p = Process(target=chain,args=(howmany,))
p.start()
output(howmany,p.pid)
def main():
childpid = 0
howmany=6
p = Process(target=chain,args=(howmany,))
p.start()
if __name__=="__main__":
main()
有与主进程利用Process创建子进程,而子进程又再创建子进程(也就是A->B->C-D),如此类推,知道howmany小于0结束。运行1结果如下:
[root@localhost ~]# ./simplechina.py
i:5 process ID:13581 parent ID13580 child ID 13582
i:4 process ID:13582 parent ID13581 child ID 13583
i:3 process ID:13583 parent ID13582 child ID 13584
i:2 process ID:13584 parent ID13583 child ID 13585
i:1 process ID:13585 parent ID13584 child ID 13586
接下来如何创建一个进程扇,也就是:
A
/ \
B C
建立simplefan.py文件,代码如下:
[root@localhost ~]# cat simplefan.py
#!/usr/bin/env python
import os
from multiprocessing import Process
def output(howmany,childpid):
info = (howmany,os.getpid(),os.getppid(),childpid)
print "i:%d process ID:%d parent ID%d child ID %d\n" % info
def fan(i):
output(i,os.getpid())
def main():
pList=[]
for i in range(6):
p = Process(target=fan,args=(i,))
pList.append(p)
for p in pList:
p.start()
for p in pList:
p.join()
if __name__=="__main__":
main()
运行结果如下:
[root@localhost ~]# ./simplefan.py
i:0 process ID:13594 parent ID13593 child ID 13594
i:2 process ID:13596 parent ID13593 child ID 13596
i:3 process ID:13597 parent ID13593 child ID 13597
i:1 process ID:13595 parent ID13593 child ID 13595
i:4 process ID:13598 parent ID13593 child ID 13598
i:5 process ID:13599 parent ID13593 child ID 13599
除了进程ID为13593的进程外,其它进程的父进程都是13593
父进程利用join方法等等所有的子进程结束。