今天看到别人的源代码中有fork
子进程来操作数据。但是由于fork
之后,没有及时的退出,导致系统中的Python进程越来越多,子进程越来越多了。自己随手写了Python下fork
进程的测试代码(来说明这个问题不一定完全合适):
code1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | def fork(a):
def now():
import datetime
return datetime.datetime.now().strftime( "%S.%f" )
import os
import time
print now(), a
if os.fork() = = 0 :
print '子进程[%s]:%s' % (now(), os.getpid())
while 1 :
a - = 10
print '子进程的a值[%s]:%s' % (now(), a)
if a < 1 :
break
print '准备退出子进程'
else :
print '父进程[%s]:%s' % (now(), os.getpid())
while 1 :
a - = 1
print '父进程的a值[%s]:%s' % (now(), a)
if a < 0 :
break
time.sleep( 1 )
print '等待子进程结束...'
try :
result = os.wait()
if result:
print '子进程:' , result[ 0 ], result[ 1 ]
else :
print '没有数据!'
except :
print '异常哦...'
print '父进程...'
print '最后的值:' ,a
|
TIPS:
os.fork()
会有两次返回值,分别是父进程和子进程的返回值
- 在父进程中,fork返回的值是子进程的PID;
- 子进程中,这个返回值为0
- 子进程会复制父进程的上下文
- 父子进程并不能确定执行顺序
os.fork()
之后,子进程一定要使用exit()
或者os._exit()
来退出子进程环境,建议使用os._exit()
os.fork()
来创建子进程的这个代码并不是很通适,Linux是没问题的,在Windows下就是不能用的,而官方文档也有类似表述:
Note that some platforms including FreeBSD <= 6.3, Cygwin and OS/2 EMX have known issues when using fork() from a thread
Availability: Unix.