📜  Python| os.pipe() 方法

📅  最后修改于: 2022-05-13 01:55:10.883000             🧑  作者: Mango

Python| os.pipe() 方法

Python中的OS 模块提供了与操作系统交互的功能。操作系统属于 Python 的标准实用程序模块。该模块提供了一种使用操作系统相关功能的可移植方式。

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

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

代码: 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