Newbie question: how to make os.fork() and os.pipe() work

Kevin O'Gorman kogorman at pacbell.net
Fri Oct 6 00:19:24 EDT 2000


I've got a pretty basic book, and online docs, and I've done
my best to RTFM, but I'm now at my frustration point.

I can use os.fork() to create a child process, but I cannot
get messages from the child to the parent through the pipe
I've created.

If anyone's got a little sample program that shows how this
is done, I'd sure appreciate it.

At the moment, my (non-working) version complains that the
parent's attemts to read the pipe are failing.  It looks
like this:


#! /usr/bin/python
# $Id: fork.py,v 1.2 2000/10/06 04:17:32 kevin Exp kevin $
 
import string
import sys
import re
import os
 
print "Running $Id: fork.py,v 1.2 2000/10/06 04:17:32 kevin Exp kevin $"
 
osi=sys.stdin
oso=sys.stdout
ose=sys.stderr
 
rw=os.pipe()
r=rw[0]
w=rw[1]
print "Reading on",r,", and writing on",w
child=os.fork()
if child==0:
        sys.stderr.write("In child\n")
        os.close(1)
        os.dup(w)
        sys.stdout=os.fdopen(1,"w")
        os.close(r)
        os.close(w)
 
        sys.stderr.write("Writing\n")
        print "foo"
        print "bar"
        print "foobuar"
        sys.stdout.close()
        sys.exit(0)
 
os.close(0)
os.dup(r)
sys.stdin=os.fdopen(r)
os.close(r)
os.close(w)
 
print "Stdin is ",sys.stdin
print "about to read"
lin=sys.stdin.readline()
if not lin:
        print "Read failed",lin
        sys.exit(1)
while lin:
        print lin
       
lin=sys.stdin.readline()                                                



-- 
Kevin O'Gorman  (805) 650-6274  mailto:kogorman at pacbell.net
Permanent e-mail forwarder:  mailto:Kevin.O'Gorman.64 at Alum.Dartmouth.org
At school: mailto:kogorman at cs.ucsb.edu
Web: http://www.cs.ucsb.edu/~kogorman/index.html
Web: http://trixie.kosman.via.ayuda.com/~kevin/index.html



More information about the Python-list mailing list