Python中os.fork()的簡單理解

Python中,通過os.fork()會做下面的事情
(1)創建子進程,子進程會複製父進程的數據信息,然後程序就分兩個進程繼續運行後面的程序,這也是fork(分叉)名字的含義了。
(2)在父進程內,這個方法會返回子進程的編號PID。
(3)在子進程內,這個方法會返回0。
所以可以使用PID來區分兩個進程:

import os

def doing():
	print '{} : before fork'.format(os.getpid())
	pid = os.fork()
	#複製出來的子進程會在這裏繼續執行,同時pid=0
	print '{} : after  fork'.format(os.getpid())
	if pid == 0:
		# We are in the child process.
		print "{} (child) was created by {}.".format(os.getpid(), os.getppid())
	else:
		# We are in the parent process.
		print "{} (parent) created {}.".format(os.getpid(), pid)
	print '{} : end'.format(os.getpid())
	print '************************'


if __name__ == '__main__':
	doing()
85925 : before fork
85925 : after  fork
85925 (parent) created 85926.
85925 : end
************************
85926 : after  fork
85926 (child) was created by 85925.
85926 : end
************************

Process finished with exit code 0
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章