Python 中的 fork 和退出
该代码应该尝试启动服务器进程并返回。 如果端口被占用,它应该说“无法绑定到该端口”并返回。如果服务器启动,它应该打印“Bound to port 51231”并返回。但它不会返回。
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()
我可以抛出一些开关来使多处理让我这样做吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
检查此页面,它描述了如何使用 os.fork() 和 os._exit(1) 构建一个分叉到后台的守护进程。
您可能想要的原型是:
为什么分叉两次 看到这个问题(简短版本:需要孤立子进程并使其成为 init 进程的子进程)
Check this page, it describes how to use
os.fork()
andos._exit(1)
to build a daemon which forks to background.A prototype of what you perhaps want would be:
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)
为了执行您所描述的操作,我不会使用多处理,我会考虑编写 守护进程。
To do what you describe, I wouldn't use multiprocessing, I'd look into writing a daemon.
作为编写守护进程的替代方法,只需将程序编写为控制台进程(对其进行测试),并使用服务管理应用程序,例如 supervisord 将其作为服务运行。 Supervisord 还可以做更多的事情,不仅仅是将程序作为服务运行。它将监视、重新启动、记录、报告状态和状态更改,甚至提供一个最小的 Web 界面来管理您的流程。
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.