views:

54

answers:

3

This code is supposed to try and start a server process and return. If the port was taken, it should say "couldn't bind to that port" and return. If the server started, it should print "Bound to port 51231" and return. But it does not return.

import socket
from multiprocessing import Process

def serverMainLoop(s,t):
    s.listen(5)
    while 1:
        pass # server goes here

host = ''
port = 51231
so = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

try:
    so.bind((host,port))
    print "Bound to port %i"%port
    serverProcess = Process(target=serverMainloop, args=(so,60))
    serverProcess.start()
    sys.exit()
except socket.error, (value,message):
    if value==98:
        print "couldn't bind to that port"
    sys.exit()

Is there some switch I can throw that will make multiprocessing let me do this?

+1  A: 

Check this page, it describes how to use os.fork() and os._exit(1) to build a daemon which forks to background.

A prototype of what you perhaps want would be:

pid = os.fork()
if (pid == 0): # The first child.
   os.chdir("/")
   os.setsid()
   os.umask(0) 
   pid2 = os.fork() 
   if (pid2 == 0):  # Second child
     # YOUR CODE HERE
   else:
     sys.exit()    #First child exists
else:           # Parent Code
  sys.exit()   # Parent exists

For the reason why to fork twice see this Question (Short Version: It's needed to orphan the child and make it a child of the init-process)

theomega
Why fork twice?
Nathan
http://stackoverflow.com/questions/881388/what-is-the-reason-for-performing-a-double-fork-when-creating-a-daemon
theomega
+1  A: 

To do what you describe, I wouldn't use multiprocessing, I'd look into writing a daemon.

Mark
A: 

As an alternative to writing a daemon, just write your program as a console process (testing it as such), and use a service management application like supervisord to run it as a service. Supervisord also does much more that just run your program as a service. It will monitor, restart, log, report status and status changes, and even provide a minimal web interface to manage your process.

Marcelo Cantos
I would do this, but I need to log into a remote machine with an unknown configuration, upload the server, start it, and leave. This is being done from within a windows GUI application.
Nathan