fork in Python

来源:互联网 发布:牌匾设计软件 编辑:程序博客网 时间:2024/06/11 01:31

       fork 是 python linux下 os模块下的一个方法,用来创建一个子进程。今天遇到这个问题,所以找文章来稍微了解一下。以下来自http://www.myelin.co.nz/post/2003/3/13 /#200303135。不当之处多指教。


1、有时,程序在一个进程中运行可能会遇到一些问题。如进程可能会占用过多的内存或者打开太多的文件,或者根本无法运行。

2、一般来说,需要将进程分为两个,在子进程中执行一些代码,然后向父进程总返回结果。

      这个过程是通过管道来实现的。os.pipe()创建一个管道。一个管道包括两个端,一个读(父进程)一个写(子进程)。子进程将结果写入写端,然后关闭之。父进程从读端读出。

      以os.fork()创建新进程,复制所有文件描述符。则父子进程都有了管道的读端和写端的拷贝。直到管道一端的所有拷贝都被关闭,那么管道才关闭,因而在创建子进程之后需要调用os.close()关闭父进程的写端。

      所以,运行过程是:

           ---创建管道

           ---创建子进程。

   子进程:

           ----需要关闭管道读端

           ----开始执行

           ----向写端写入结果

           ----进程死亡

  父进程:

           ----关闭管道写端

          ----从读端读取数据直到子进程死亡或者关闭

          ----调用waitpid方法确保子进程已经被撤销(在FreeBSD中不这么做,那么子进程永远不会被死亡)

           ----进程输出

3、代码

#!/usr/bin/env pythonimport os, sysprint "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 objectspid = 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 upelse:    # 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