os.fork() different in cgi-script?

Juha Autero Juha.Autero at iki.fi
Wed Jul 2 17:27:46 CEST 2003


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

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

No, it isn't. The problem is that Python uses C STDIO library that has
buffered input and output. The text written in stdout is written in
buffer. Since child process created by fork() is almost identical to
parent process, it will also have a copy of stdout buffer. When
process exits, it closes stdout, which flushes the buffer. So, both
buffers are written to stdout and that causes everything to be printed
twice.

The reason why this doesn happen on command line is that buffers to
terminals are flushed after newline. You can see that by redirecting
script output to file:

$ python script.py >output
$ cat output
Content-Type: text/plain


4309
Content-Type: text/plain


4309

> I googled for this but only found a similar question from 1997 and no
> answer.

Which is strange since this common problem and has nothing to do with
Python.
-- 
Juha Autero
http://www.iki.fi/jautero/
Eschew obscurity!






More information about the Python-list mailing list