Python进程通信之匿名管道实例讲解_python

匿名管道

管道是一个单向通道,有点类似共享内存缓存.管道有两端,包括输入端和输出端.对于一个进程的而言,它只能看到管道一端,即要么是输入端要么是输出端.

os.pipe()返回2个文件描述符(r, w),表示可读的和可写的.示例代码如下:

复制代码 代码如下:

#!/usr/bin/python
import time
import os

def child(wpipe):
    print('hello from child', os.getpid())
    while True:
        msg = 'how are you\n'.encode()
        os.write(wpipe, msg)
        time.sleep(1)

def parent():
    rpipe, wpipe = os.pipe()
    pid = os.fork()
    if pid == 0:
        child(wpipe)
        assert False, 'fork child process error!'
    else:
        os.close(wpipe)
        print('hello from parent', os.getpid(), pid)
        fobj = os.fdopen(rpipe, 'r')
        while True:
            recv = os.read(rpipe, 32)
            print recv

parent()

输出如下:

复制代码 代码如下:

('hello from parent', 5053, 5054)
('hello from child', 5054)
how are you

how are you

how are you

how are you

我们也可以改进代码,不用os.read()从管道中读取二进制字节,而是从文件对象中读取字符串.这时需要用到os.fdopen()把底层的文件描述符(管道)包装成文件对象,然后再用文件对象中的readline()方法读取.这里请注意文件对象的readline()方法总是读取有换行符'\n'的一行,而且连换行符也读取出来.还有一点要改进的地方是,把父进程和子进程的管道中不用的一端关闭掉.

复制代码 代码如下:

#!/usr/bin/python
import time
import os

def child(wpipe):
    print('hello from child', os.getpid())
    while True:
        msg = 'how are you\n'.encode()
        os.write(wpipe, msg)
        time.sleep(1)

def parent():
    rpipe, wpipe = os.pipe()
    pid = os.fork()
    if pid == 0:
        os.close(rpipe)
        child(wpipe)
        assert False, 'fork child process error!'
    else:
        os.close(wpipe)
        print('hello from parent', os.getpid(), pid)
        fobj = os.fdopen(rpipe, 'r')
        while True:
            recv = fobj.readline()[:-1]
            print recv

parent()

输出如下:

复制代码 代码如下:

('hello from parent', 5108, 5109)
('hello from child', 5109)
how are you
how are you
how are you

如果要与子进程进行双向通信,只有一个pipe管道是不够的,需要2个pipe管道才行.以下示例在父进程新建了2个管道,然后再fork子进程.os.dup2()实现输出和输入的重定向.spawn功能类似于subprocess.Popen(),既能发送消息给子进程,由能从子子进程获取返回数据.

复制代码 代码如下:

#!/usr/bin/python
#coding=utf-8
import os, sys

def spawn(prog, *args):
    stdinFd = sys.stdin.fileno()
    stdoutFd = sys.stdout.fileno()

    parentStdin, childStdout = os.pipe()
    childStdin, parentStdout= os.pipe()

    pid = os.fork()
    if pid:
        os.close(childStdin)
        os.close(childStdout)
        os.dup2(parentStdin, stdinFd)#输入流绑定到管道,将输入重定向到管道一端parentStdin
        os.dup2(parentStdout, stdoutFd)#输出流绑定到管道,发送到子进程childStdin
    else:
        os.close(parentStdin)
        os.close(parentStdout)
        os.dup2(childStdin, stdinFd)#输入流绑定到管道
        os.dup2(childStdout, stdoutFd)
        args = (prog, ) + args
        os.execvp(prog, args)
        assert False, 'execvp failed!'

if __name__ == '__main__':
    mypid = os.getpid()
    spawn('python', 'pipetest.py', 'spam')

    print 'Hello 1 from parent', mypid #打印到输出流parentStdout, 经管道发送到子进程childStdin
    sys.stdout.flush()
    reply = raw_input()
    sys.stderr.write('Parent got: "%s"\n' % reply)#stderr没有绑定到管道上

    print 'Hello 2 from parent', mypid
    sys.stdout.flush()
    reply = sys.stdin.readline()#另外一种方式获得子进程返回信息
    sys.stderr.write('Parent got: "%s"\n' % reply[:-1])

pipetest.py代码如下:

复制代码 代码如下:

#coding=utf-8
import os, time, sys

mypid = os.getpid()
parentpid = os.getppid()
sys.stderr.write('child %d of %d got arg: "%s"\n' %(mypid, parentpid, sys.argv[1]))

for i in range(2):
    time.sleep(3)
    recv = raw_input()#从管道获取数据,来源于父经常stdout
    time.sleep(3)
    send = 'Child %d got: [%s]' % (mypid, recv)
    print(send)#stdout绑定到管道上,发送到父进程stdin
    sys.stdout.flush()

输出:

复制代码 代码如下:

child 7265 of 7264 got arg: "spam"
Parent got: "Child 7265 got: [Hello 1 from parent 7264]"
Parent got: "Child 7265 got: [Hello 2 from parent 7264]"

时间: 2024-09-19 10:00:02

Python进程通信之匿名管道实例讲解_python的相关文章

进程通信系列-匿名管道

匿名管道只能在本机由父进程至子进程,优点在于子进程方便重定向,常用于应用程序内部 注意判断此进程是父类还是子类,代码长度一般 匿名管道类 #include "stdafx.h" #include "niming.h" #include <iostream> using namespace std; niming::niming(void) { } niming::~niming(void) { } int niming::build() { SECURI

Linux下C编程,进程通信之无名管道通信

最近在看进程间的通信,下面说说管道通信之无名管道. 1.概述 管道是Linux中很重要的一种通信方式,他是把一个程序的输出直接连接到另一个程序的输入,并且管道具有队列的特性.如Linux命令,"ps -ef | grep root".如下图所示: 2.无名管道 2.1特点 (1)它只能用于具有亲缘关系的进程之间的通信(也就是父子进程或者兄弟进程之间). (2)它是一个半双工的通信模式,具有固定的读端和写端. (3)管道也可以看成是一种特殊的文件,对于它的读写也可以使用普通的read.w

python 解析XML python模块xml.dom解析xml实例代码_python

一 .python模块 xml.dom 解析XML的APIminidom.parse(filename)加载读取XML文件 doc.documentElement获取XML文档对象 node.getAttribute(AttributeName)获取XML节点属性值 node.getElementsByTagName(TagName)获取XML节点对象集合 node.childNodes #返回子节点列表. node.childNodes[index].nodeValue获取XML节点值 nod

Python使用urllib2获取网络资源实例讲解_python

这是具有利用不同协议获取URLs的能力,他同样提供了一个比较复杂的接口来处理一般情况,例如:基础验证,cookies,代理和其他.它们通过handlers和openers的对象提供.urllib2支持获取不同格式的URLs(在URL的":"前定义的字串,例如:"ftp"是"ftp:python.ort/"的前缀),它们利用它们相关网络协议(例如FTP,HTTP)进行获取.这篇教程关注最广泛的应用--HTTP.对于简单的应用,urlopen是非常容

python进程管理工具supervisor使用实例_python

平时我们写个脚本,要放到后台执行去,我们怎么做呢? 复制代码 代码如下: nohup python example.py 2>&1 /dev/null & 用tumx或者screen? 但是用着可能都不爽,今天就看看python里面的一个进程管理工具supervisor: 官方说:Supervisor: A Process Control System 说白了他就是一个demon程序,他来帮助我们完成对我们想要托管的脚本也好程序也好,好好的照料: 1.安装 python的东西就是好安

python中的多重继承实例讲解_python

python和C++一样,支持多继承.概念虽然容易,但是困难的工作是如果子类调用一个自身没有定义的属性,它是按照何种顺序去到父类寻找呢,尤其是众多父类中有多个都包含该同名属性. 对经典类和新式类来说,属性的查找顺序是不同的.现在我们分别看一下经典类和新式类两种不同的表现: 经典类: 复制代码 代码如下: #! /usr/bin/python # -*- coding:utf-8 -*- class P1():     def foo(self):         print 'p1-foo' c

python使用xmlrpc实例讲解_python

RPC是Remote Procedure Call的缩写,翻译成中文就是远程方法调用,是一种在本地的机器上调用远端机器上的一个过程(方法)的技术,这个过程也被大家称为"分布式计算",是为了提高各个分立机器的"互操作性"而发明出来的技术. XML-RPC的全称是XML Remote Procedure Call,即XML远程方法调用. 它是一套允许运行在不同操作系统.不同环境的程序实现基于Internet过程调用的规范和一系列的实现.这种远程过程调用使用http作为传

Python collections模块实例讲解_python

collections模块基本介绍 我们都知道,Python拥有一些内置的数据类型,比如str, int, list, tuple, dict等, collections模块在这些内置数据类型的基础上,提供了几个额外的数据类型: 1.namedtuple(): 生成可以使用名字来访问元素内容的tuple子类2.deque: 双端队列,可以快速的从另外一侧追加和推出对象3.Counter: 计数器,主要用来计数4.OrderedDict: 有序字典5.defaultdict: 带有默认值的字典 n

Python中apply函数的用法实例教程_python

一.概述: python apply函数的具体含义如下:  apply(func [, args [, kwargs ]]) 函数用于当函数参数已经存在于一个元组或字典中时,间接地调用函数.args是一个包含将要提供给函数的按位置传递的参数的元组.如果省略了args,任何参数都不会被传递,kwargs是一个包含关键字参数的字典.   apply()的返回值就是func()的返回值,apply()的元素参数是有序的,元素的顺序必须和func()形式参数的顺序一致 二.使用示例: 下面给几个例子来详