os.fork() different in cgi-script?

Michael Coleman mkc at stowers-institute.org
Wed Jul 2 16:50:03 CEST 2003


"Andreas Kuntzagk" <andreas.kuntzagk at mdc-berlin.de> writes:
> def main():
>     print "Content-Type: text/plain\n\n"
>     print os.getpid()
> 
>     childPID = os.fork()
>     if childPID == 0:
>         sys.exit()
>     else:
>         os.wait()
>     
> if __name__ == "__main__":
>     main()
> 
> when run on a shell, gives the result:
> ---------------------------
> Content-Type: text/plain
> 
> 
> 20953
> ----------------------------
> 
> but run as a cgi-script it gives:
> ---------------------------
> 21039
> Content-Type: text/plain
> 
> 
> 21039
> ---------------------------
> So it looks the main() is run 2 times. 
> Is it so? And if yes, why?

Probably because stdout is being buffered here.  The pid got written in the buffer (but not yet actually printed), then the process was forked, then the buffer got flushed (written out) by each child.

One solution would be to make sure everything is flushed before you fork.

Mike

-- 
Mike Coleman, Scientific Programmer, +1 816 926 4419
Stowers Institute for Biomedical Research
1000 E. 50th St., Kansas City, MO  64110




More information about the Python-list mailing list