Nathan
Nathan

Reputation: 6225

Fork and exit in Python

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?

Upvotes: 0

Views: 11374

Answers (3)

theomega
theomega

Reputation: 32051

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)

Upvotes: 4

Marcelo Cantos
Marcelo Cantos

Reputation: 186098

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.

Upvotes: 0

Mark
Mark

Reputation: 108567

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

Upvotes: 1

Related Questions