os.fork

来源:互联网 发布:淘宝墙上挂的饰品 编辑:程序博客网 时间:2024/06/05 03:14
         python的os module中有fork()函数用于生成子进程,生成的子进程是父进程的镜像,但是它们有各自的地址空间,子进程复制一份父进程内存给自己,两个进程之间的执行是相互独立的,其执行顺序可以是不确定的、随机的、不可预测的,这点与多线程的执行顺序相似。  
[python] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. import os  
  2.   
  3. def child():  
  4.     print 'A new child:', os.getpid()  
  5.     print 'Parent id is:', os.getppid()  
  6.     os._exit(0)  
  7.   
  8. def parent():  
  9.     while True:  
  10.         newpid=os.fork()  
  11.         print newpid  
  12.         if newpid==0:  
  13.             child()  
  14.         else:  
  15.             pids=(os.getpid(),newpid)  
  16.             print "parent:%d,child:%d"%pids  
  17.             print "parent parent:",os.getppid()         
  18.         if raw_input()=='q':  
  19.             break  
  20.   
  21. parent()  

       在我们加载了os模块之后,我们parent函数中fork()函数生成了一个子进程,返回值newpid有两个,一个为0,用以表示子进程,一个是大于0的整数,用以表示父进程,这个常数正是子进程的pid. 通过print语句我们可以清晰看到两个返回值。如果fork()返回值是一个负值,则表明子进程生成不成功(这个简单程序中没有考虑这种情况)。如果newpid==0,则表明我们进入到了子进程,也就是child()函数中,在子进程中我们输出了自己的id和父进程的id。如果进入了else语句,则表明newpid>0,我们进入到父进程中,在父进程中os.getpid()得到自己的id,fork()返回值newpid表示了子进程的id,同时我们输出了父进程的父进程的id. 通过实验我们可以看到if和else语句的执行顺序是不确定的,子、父进程的执行顺序由操作系统的调度算法来决定。


#!/usr/bin/python# -*- coding: UTF-8 -*-import os, sysprint("The child will write text to a pipe and ")print("the parent will read the text written by child...")# file descriptors r, w for reading and writingr, w = os.pipe()print(os.getpid())print("over")processid = os.fork()print(processid)if processid:    # This is the parent process    # Closes file descriptor w    os.close(w)    r = os.fdopen(r)    print("parent",os.getpid(),os.getppid())    print("Parent reading")    str = r.read()    print("text =", str)    sys.exit(0)else:    # This is the child process    os.close(r)    w = os.fdopen(w, 'w')    print("child",os.getpid(),os.getppid())    print("Child writing")    w.write("Text written by child...")    w.close()    print("Child closing")    sys.exit(0)

0 0
原创粉丝点击