📜  Python| os.pipe2() 方法

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

Python| os.pipe2() 方法

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

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

代码:使用 os.pipe2() 方法创建带有自动设置标志的管道
# Python program to explain os.pipe2() method 
  
# importing os module 
import os
  
  
# Create a pipe with
# flag set automatically
# os.O_NONBLOCK flag tells 
# that file descriptor 
# is in non-blocking mode
flags = os.O_NONBLOCK
r, w = os.pipe2(flags)
  
# 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 child 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

参考: https://docs。 Python.org/3/library/os.html#os.pipe2