fork 是
1、有时,程序在一个进程中运行可能会遇到一些问题。如进程可能会占用过多的内存或者打开太多的文件,或者根本无法运行。
2、一般来说,需要将进程分为两个,在子进程中执行一些代码,然后向父进程总返回结果。
3、代码
#!/usr/bin/env python
import os, sys
print "I'm going to fork now - the child will write something to a pipe, and the parent will read it back"
r, w = os.pipe() # these are file descriptors, not file objects
pid = os.fork()
if pid:
# we are the parent
os.close(w) # use os.close() to close a file descriptor
r = os.fdopen(r) # turn r into a file object
print "parent: reading"
txt = r.read()
os.waitpid(pid, 0) # make sure the child process gets cleaned up
else:
# we are the child
os.close(r)
w = os.fdopen(w, 'w')
print "child: writing"
w.write("here's some text from the child")
w.close()
print "child: closing"
sys.exit(0)
print "parent: got it; text =", txt