Random and fork

Peter Otten __peter__ at web.de
Wed Feb 6 11:47:38 EST 2013


Julien Le Goff wrote:

> Hi everyone,
> 
> Today I came accross a behaviour I did not expect in python (I am using
> 2.7). In my program, random.random() always seemed to return the same
> number; it turned out to be related to the fact that I was using os.fork.
> 
> See below a small program that illustrates this. It is easily fixed, but
> I'm interested in knowing why this happens. Can anybody give me a hint?
> Thanks!

Those numbers are "pseudo"-random numbers -- the sequence of numbers 
generated is fully determined by the state of the random number generator. 
That state like anything else is copied by fork(). I you need "better" 
randomness you can use random.SystemRandom:

> import random
> import os

random = random.SystemRandom()
 
> for i in xrange(10):
>     pid = os.fork()
>     if pid == 0:
>         # uncommenting this fixes the problem
>         # random.seed(os.getpid())
>         print random.random()
>         os._exit(0)
> 
> os.wait()





More information about the Python-list mailing list