Created
          February 12, 2015 22:29 
        
      - 
      
- 
        Save alejandrobernardis/237a6cc62d8eb65f66bd to your computer and use it in GitHub Desktop. 
    tornado forking
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | # | |
| # https://groups.google.com/d/msg/python-tornado/1LsOhqwOOTI/2Sp7RSM7sfcJ | |
| # | |
| # | |
| import os | |
| import time | |
| from tornado import gen, ioloop, httpserver, web | |
| def fork_processes(num_processes): | |
| children = {} | |
| def start_child(_i): | |
| pid = os.fork() | |
| if pid == 0: | |
| return None | |
| else: | |
| children[pid] = _i | |
| return pid | |
| for i in range(num_processes): | |
| _id = start_child(i) | |
| if _id is None: | |
| return None | |
| return children | |
| class MainPageHandler(web.RequestHandler): | |
| @gen.coroutine | |
| def get(self, *args, **kwargs): | |
| self.finish(dict(key=1)) | |
| if __name__ == "__main__": | |
| http_server = httpserver.HTTPServer(None) | |
| http_server.bind(port=8320) | |
| child_processes = fork_processes(2) | |
| if isinstance(child_processes, dict): | |
| print u"Master process: child data={}".format(child_processes) | |
| time.sleep(5) | |
| else: | |
| child_pid = os.getpid() | |
| print u"Child process [{}] started".format(child_pid) | |
| _ioLoop = ioloop.IOLoop.instance() | |
| _ioLoop.make_current() | |
| application = web.Application([ | |
| (r"/", MainPageHandler), | |
| ]) | |
| http_server.request_callback = application | |
| http_server.io_loop = _ioLoop | |
| http_server.add_sockets(http_server._pending_sockets) | |
| _ioLoop.start() | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment