Python 中fork()理解
阿新 • • 發佈:2018-12-13
參考:多程序- 廖雪峰的官方網站 首先,在python中我們要實現多程序,有兩個模組可以用: 1)os中的fork()函式 2)multiprocessing模組 那麼這兩個模組有什麼區別呢? 在fork()是基於unix/linux核心的函式,在windows中無法使用,因此multiprocessing模組作為跨平臺的存在。
fork()
作為例子,我們先把參考部落格中的例子拿過來
# multiprocessing.py import os print 'Process (%s) start...' % os.getpid() pid = os.fork() if pid==0: print 'I am child process (%s) and my parent is %s.' % (os.getpid(), os.getppid()) else: print 'I (%s) just created a child process (%s).' % (os.getpid(), pid)
os.fork()這個函式,對於父程序,返回的是子程序的pid,對於子程序,返回的是0. 而通過os.getpid()得到的是當前的pid,os.getppid()得到的是父程序的pid。
更進一步的分析:
# multiprocessing.py import os print 'Process (%s) start...' % os.getpid() fork_num = 0 while(fork_num < 3): pid = os.fork() fork_num += 1 if pid==0: print 'I am child process (%s) and my parent is %s.' % (os.getpid(), os.getppid()) else: print 'I (%s) just created a child process (%s).' % (os.getpid(), pid)
在執行之前,我們分析可以得到,經過三次迴圈,應該有8個程序 執行結果:
Process (427) start... I (427) just created a child process (428). I (427) just created a child process (429). I am child process (428) and my parent is 427. I (427) just created a child process (430). I (428) just created a child process (431). I am child process (431) and my parent is 428. I (428) just created a child process (432). I (431) just created a child process (433). I am child process (433) and my parent is 431. I am child process (430) and my parent is 427. I am child process (429) and my parent is 427. I am child process (432) and my parent is 428. I (429) just created a child process (434). I am child process (434) and my parent is 429.
該函式在執行時,是將程式碼在子程序中複製了一份