Attachment 'fork_pipe.py'

Download

   1 #!/usr/bin/python
   2 # -*- coding: utf-8 -*-
   3 
   4 import os
   5 import time
   6 import sys
   7 
   8 # Vytvorime pipe
   9 (r_pipe,w_pipe)=os.pipe()
  10 print "Pipe je",r_pipe,w_pipe
  11 # Zavolame fork
  12 pid_chld=os.fork()
  13 # child dostane vratene 0, parent dostane PID childa
  14 # oba procesy zdedia pipe, ale jeden bude citat a druhy zapisovat
  15 if pid_chld==0:
  16         print "Child bezi"
  17         # child si vezme r_pipe a vytvori z neho pythonovsky
  18         # file objekt
  19         file_read=os.fdopen(r_pipe,"r")
  20         # precita 20 riadkov zo vstupu (retazce)
  21         for i in range(20):
  22                 input=file_read.readline()
  23                 # vypisuje druhe mocniny
  24                 print "%d^2=%d" % (int(input),int(input)*int(input))
  25 else:
  26         print "Parent bezi"
  27         file_write=os.fdopen(w_pipe,"w")
  28         for i in range(20):
  29                 file_write.write("%d\n" % i)
  30                 # ak nasledujuci riadok zakomentujeme,
  31                 # parent bude pisat do buffra,
  32                 # ktory sa vypluje pri zatvoreni
  33                 file_write.flush()
  34                 print "%d zapisovane" % i
  35                 time.sleep(0.1)
  36         file_write.close()
  37         # treba pockat, kym neskonci child
  38         # inak si nestihne prebrat udaje
  39         os.wait()

Attached Files

To refer to attachments on a page, use attachment:filename, as shown below in the list of files. Do NOT use the URL of the [get] link, since this is subject to change and can break easily.

You are not allowed to attach a file to this page.