os.fork() different in cgi-script?

Erwin S. Andreasen erwin at andreasen.com
Wed Jul 2 17:47:48 CEST 2003

"Andreas Kuntzagk" <andreas.kuntzagk at mdc-berlin.de> writes:

> following code:

>     print "Content-Type: text/plain\n\n"
>     print os.getpid()
>     childPID = os.fork()
>     if childPID == 0:
>         sys.exit()
>     else:
>         os.wait()


> So it looks the main() is run 2 times. 
> Is it so? And if yes, why?

The problem is buffering. When you run your script from the command
line, the standard output is a terminal and becomes line-buffered.
Thus at the time you fork, the stdout buffer has been flushed.

When you run it as a CGI script, stdout is a socket and thus not a
terminal -- so it becomes block buffered. At the time you fork, each
copy of stdout holds all of our unflushed output. When the two
processes exit they will both flush the output, resulting in it being
printed twice.

You can use sys.stdout.flush() to flush the pending output before

<erwin at andreasen.org>                           Herlev, Denmark     
<URL:http://www.andreasen.org/>                             <*>   

More information about the Python-list mailing list