forking + stdout = confusion

Steve Spicklemire steve at estel.uindy.edu
Mon Apr 12 06:38:47 EDT 1999


Hi Clarence,

>>>>> "Clarence" == Clarence Gardner <clarence at silcom.com> writes:

[snip]

    Clarence> def LateShift():
    Clarence>     OutputID = `os.getpid()`
    Clarence>     Child = os.fork()
    Clarence>     if Child:
    Clarence>         print 'content-type: text/plain'
    Clarence>         print
    Clarence>         print '''The program is waiting to run later.  The output will
    Clarence>                 be available with the id number of %s.
    Clarence>                 ''' % OutputID
    Clarence>         sys.exit(0)
    Clarence>     sys.stdin.close()
    Clarence>     sys.stdout.close()
    Clarence>     sys.stderr.close()
    Clarence>     sys.stdout = open(os.path.join(SpoolDir, OutputID), 'w')
    Clarence>     sys.stderr = sys.stdout
    Clarence>     time.sleep(15)

[snip]

Hmm.. the following code works for me:

    try:
        serr = sys.stderr
        sys.stderr = sys.stdout

        sys.stdout.flush()
        pid = os.fork()
        if pid:
            #
            # OK...we are the parent process
            #
            sys.stdout.close()
            sys.stdin.close()

            os.wait()
        else:
            sys.stderr = serr
            sys.stdout.close()
            sys.stdin.close()

            ... on to do time consuming task.....

    Clarence> I thought that maybe sys.stdout was using a dup()'ed
    Clarence> copy of stdout, but I checked sys.stdout.fileno() and it
    Clarence> was 1, so that doesn't seem to be the case.

    Clarence> Can anyone hazard a guess (or see right off the top of
    Clarence> his head) what's going on here?  Thanks for any help.

I'm not sure, but I think sys.stdout is always 1. I think you need to close
sys.stdxxx in both processes explicitly. At least it works on my systems.

good luck!
-steve

    Clarence> -- -=-=-=-=-=-=-=-= Clarence Gardner AvTel
    Clarence> Communications Software Products and Services Division
    Clarence> clarence at avtel.com










More information about the Python-list mailing list