1. 程式人生 > >python-無名管道進程通信

python-無名管道進程通信

logs getpid line child div nbsp fail tdi pipe()

 1 #!/usr/bin/python
 2 #coding=utf-8
 3 import sys,os
 4 from time import sleep
 5 
 6 (r,w)=os.pipe()   #創建無名管道,返回兩個整數,代表兩個管道文件,且代表的功能是(r,w)
 7 pid=os.fork()
 8 
 9 if pid<0:
10     print "fail to fork"
11 elif pid==0:
12     print "child",os.getpid()
13     os.close(w)   #關閉文件描述符
14     r=os.fdopen(r,"
r") #把底層的文件描述符轉換為文件對象。 15 while True: 16 buf=r.readline() 17 print "buf:",buf 18 sys.stdout.flush() 19 print "child close" 20 else: 21 print "parent:",os.getpid() 22 os.close(r) 23 w=os.fdopen(w,w) 24 while True: 25 buf=sys.stdin.readline() 26
w.write(buf) 27 w.flush() 28 #無名管道是不會創建實體文件

python-無名管道進程通信