Fork and exit in Python

萝らか妹 提交于 2019-12-12 10:20:59

问题


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:


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)




回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/3355995/fork-and-exit-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!