進程可以通過調用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方法等等所有的子進程結束。