在Python中分叉并退出 [英] Fork and exit in Python
问题描述
该代码应尝试启动服务器进程并返回. 如果使用了端口,则应该说无法绑定到该端口"并返回.如果服务器启动,则应打印绑定到端口51231"并返回.但是它不会返回.
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?
推荐答案
检查此页面,它描述了如何使用os.fork()
和os._exit(1)
来构建派生到后台的守护程序.
Check this page, it describes how to use os.fork()
and os._exit(1)
to build a daemon which forks to background.
您可能想要的原型是:
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)
这篇关于在Python中分叉并退出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!