os.pipe() 典型用法:
#!/usr/bin/python
import os, sys
print "The child will write text to a pipe and "
print "the parent will read the text written by child..."
# file descriptors r, w for reading and writing
r, w = os.pipe()
processid = os.fork()
if processid:
# This is the parent process
# Closes file descriptor w
os.close(w)
r = os.fdopen(r)
print "Parent reading"
str = r.read()
print "text =", str
os.waitpid(processid, 0) # wait for child process terminate
sys.exit(0)
else:
# This is the child process
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)os.pipe() 的代码实现:
Tracing into module of os (os.py), and find there nothing about function of pipe(), except the following code clips:
_names = sys.builtin_module_names # names of built-in modules, with Windows OS, there will be an item of ‘nt‘ within this tuple, while on Posix (Unix, linux), there will be an item of ‘posix‘
# Note: more names are added to __all__ later.
__all__ = ["altsep", "curdir", "pardir", "sep", "extsep", "pathsep", "linesep",
"defpath", "name", "path", "devnull",
"SEEK_SET", "SEEK_CUR", "SEEK_END"]
def _get_exports_list(module): # this function will get all the attributes which not starts with "_"
try:
return list(module.__all__)
except AttributeError:
return [n for n in dir(module) if n[0] != ‘_‘]
if ‘posix‘ in _names:
name = ‘posix‘
linesep = ‘\n‘
from posix import * # import all the attributes of posix, within which pipe() is implemented as well as other posix system calls
try:
from posix import _exit
except ImportError:
pass
import posixpath as path # that‘s where os.path come from
import posix
__all__.extend(_get_exports_list(posix)) # add all the attributes of posix to var __all__
del posix
os.pipe() 的其他用法:
Another scenario of using os.pipe() is subprocess. The following source code comes from subprocess.py
os.pipe learning tips,布布扣,bubuko.com
原文:http://blog.csdn.net/ispcfs/article/details/21468951