zoukankan      html  css  js  c++  java
  • python管道pipe

    1.什么是管道
    Linux进程间通信方式的一种,管道有两端,读端和写端。创建管道,然后从父进程fork出子进程,
    父进程和子进程拥有共同的读写文件描述符,可以实现子进程写文件,父进程读文件的操作。
    示意图如下:

    2.具体操作
    子进程关闭读端,父进程关闭写端,子进程负责写,父进程负责读。
    代码示例如下:

    import os, time, sys
    pipe_name = 'pipe_test'
    
    def child( ):
        pipeout = os.open(pipe_name, os.O_WRONLY)
        counter = 0
        while True:
            time.sleep(1)
            os.write(pipeout, 'Number %03d
    ' % counter)
            counter = (counter+1) % 5
    
    def parent( ):
        pipein = open(pipe_name, 'r')
        while True:
            line = pipein.readline()[:-1]
            print 'Parent %d got "%s" at %s' % (os.getpid(), line, time.time( ))
    
    if not os.path.exists(pipe_name):
        os.mkfifo(pipe_name)  
    pid = os.fork()    
    if pid != 0:
        parent()
    else:       
        child()
    

    运行结果:

  • 相关阅读:
    安装完openfire之后打不开的解决方案
    iOS中动画的简单使用
    iOS中的多线程及GCD
    iOS 架构模式-MVVM
    iOS
    iOS 下拉刷新 上拉加载实现原理
    iOS
    iOS 中的XML解析代码(SAX)
    iOS
    iOS中的网络请求 和 网络监测
  • 原文地址:https://www.cnblogs.com/shijingjing07/p/7899611.html
Copyright © 2011-2022 走看看