CoderTag CoderTag -4 years ago 88
Python Question

Two different child process not generating unique number

Why two unique child process not generating unique random number?

import os
import string
import random

def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
print ''.join(random.choice(chars) for x in range(size)).lower()
os._exit(0)

for i in range(2):
newpid = os.fork()
if newpid == 0:
id_generator()
else:
print "Parent"


Output is showing same random number:

Parent
Parent
q52mno
q52mno

Answer Source

When you import the random module, it gives the RNG a default seed. Then when you fork, the child process inherits this seed. So both child processes are starting with the same default seed.

You need to call random.seed() in each process with different arguments, perhaps add the PID to the time.

for i in range(2):
  newpid = os.fork()
  if newpid == 0:
     random.seed(os.pid() + time.time())
     id_generator()
  else:
    print "Parent"

If you know your Python implementation uses the operating system's good source of randomness, you could just call:

random.seed()

with no arguments in each process.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download