os.fork

         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, sys

print("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 writing
r, 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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值