]> git.ipfire.org Git - thirdparty/tornado.git/commitdiff
When forking multiple processes, properly initialize the random seed 138/head
authorAlberto García Hierro <alberto@garciahierro.com>
Mon, 13 Sep 2010 18:10:23 +0000 (20:10 +0200)
committerAlberto García Hierro <alberto@garciahierro.com>
Mon, 13 Sep 2010 18:30:52 +0000 (20:30 +0200)
Avoid seeding the random module with the same value in all processes.
If available, use the same method used by random.py, otherwise
generate a seed using the current time in milliseconds and the pid.

tornado/httpserver.py

index be52c9de9087cdc1181bba35e62525523d08302a..b85704b44e3ffdadbf413606fc322493f80b4b6b 100644 (file)
@@ -203,6 +203,17 @@ class HTTPServer(object):
             logging.info("Pre-forking %d server processes", num_processes)
             for i in range(num_processes):
                 if os.fork() == 0:
+                    import random
+                    from binascii import hexlify
+                    try:
+                        # If available, use the same method as
+                        # random.py
+                        seed = long(hexlify(os.urandom(16)), 16)
+                    except NotImplementedError:
+                        # Include the pid to avoid initializing two
+                        # processes to the same value
+                        seed(int(time.time() * 1000) ^ os.getpid())
+                    random.seed(seed)
                     self.io_loop = ioloop.IOLoop.instance()
                     self.io_loop.add_handler(
                         self._socket.fileno(), self._handle_events,