《操作系统》的实验代码。
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

23 lines
733 B

  1. #!/usr/bin/env python
  2. # -*- encoding: utf8 -*-
  3. import os, sys
  4. print "I'm going to fork now - the child will write something to a pipe, and the parent will read it back"
  5. r, w = os.pipe() # r,w是文件描述符, 不是文件对象
  6. pid = os.fork()
  7. if pid:
  8. # 父进程
  9. os.close(w) # 关闭一个文件描述符
  10. r = os.fdopen(r) # 将r转化为文件对象
  11. print "parent: reading"
  12. txt = r.read()
  13. os.waitpid(pid, 0) # 确保子进程被撤销
  14. else:
  15. # 子进程
  16. os.close(r)
  17. w = os.fdopen(w, 'w')
  18. print "child: writing"
  19. w.write("here's some text from the child")
  20. w.close()
  21. print "child: closing"
  22. sys.exit(0)
  23. print "parent: got it; text =", txt