Python os.pipe() - 创建管道

Python os.pipe()

Python os模块中的所有函数在文件名和路径无效或不可访问,或其他参数类型正确但操作系统不接受的情况下都会引发OSError。

Python中的os.pipe()方法用于创建管道。管道是将信息从一个进程传递到另一个进程的方法。它只提供单向通信,传递的信息由系统保存,直到接收进程读取。

语法:os.pipe()

参数:不需要参数

返回类型:该方法返回一对文件描述符(r, w),分别用于读取和写入。

示例1

使用os.pipe()方法

# Python program to explain os.pipe() method 
  
# importing os module 
import os
  
  
# Create a pipe
r, w = os.pipe()
  
# The returned file descriptor r and w
# can be used for reading and
# writing respectively.
  
# We will create a child process
# and using these file descriptor
# the parent process will write 
# some text and child process will
# read the text written by the parent process
  
# Create a child process
pid = os.fork()
  
# pid greater than 0 represents
# the parent process
if pid > 0:
  
    # This is the parent process 
    # Closes file descriptor r
    os.close(r)
  
    # Write some text to file descriptor w 
    print("Parent process is writing")
    text = b"Hello child process"
    os.write(w, text)
    print("Written text:", text.decode())
  
      
else:
  
    # This is the parent process 
    # Closes file descriptor w
    os.close(w)
  
    # Read the text written by parent process
    print("\nChild Process is reading")
    r = os.fdopen(r)
    print("Read text:", r.read())

输出:

Parent process is writing
Text written: Hello child process

Child Process is reading
Text read: Hello child process

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程