Python方法Pipe()创建一个管道并返回一对分别可用于读取和写入的文件描述符(r,w
os.pipe() - 语法
os.pipe()
os.pipe() - 返回值
此方法返回一对文件描述符。
os.pipe() - 示例
以下示例显示了Pipe()方法的用法。
#!/usr/bin/pythonimport os, sys
print "The child will write text to a pipe and " print "the parent will read the text written by child..."
# 文件描述符 r, w 用于读写 r, w=os.pipe()
processid=os.fork() if processid: # 这是父进程关闭文件描述符 w os.close(w) r=os.fdopen(r) print "Parent reading" str=r.read() print "text =", str
sys.exit(0) else: # 这是子进程 os.close(r) w=os.fdopen(w, w) print "Child writing" w.write("Text written by child...") w.close() print "Child closing" sys.exit(0)
当无涯教程运行上面的程序时,它产生以下输出-
The child will write text to a pipe and the parent will read the text written by child... Parent reading Child writing Child closing text=Text written by child...