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
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值