我有这段代码:
class Server(object):
servers = []
def __init__(self, name, host, port, process):
self.name = name.lower()
self.host, self.port = host, port
self.process = process
self.pid = self.process.pid
@staticmethod
def register(server):
Server.servers.append(server)
@staticmethod
def unregister(server):
Server.servers.remove(server)
def start_waitress(host='0.0.0.0', port=8080):
args = ['--port={}'.format(port),
'--host={}'.format(host), 'yarr.wsgi:application']
subprocess.call(['waitress-serve'] + args)
...
host, port = '0.0.0.0', 8080
process = multiprocessing.Process(target=start_waitress)
process.start()
Server.register(Server('waitress', host, port, process))
...
for server in Server.servers:
if server.name == 'waitress':
server.process.terminate() # Here's the problem
Server.unregister(server)
break
问题是我无法在启动后终止进程。
我可以终止流程的唯一方法是运行kill <pid>
。
如何终止该过程?
答案 0 :(得分:0)
正如J.F. Sebastian所说,waitress-serve
守护自己。
我无法使用multiprocessing
解决此问题,但我找到了subprocess
的解决方案。
而不是创建multiprocessing.Process
我正在调用subprocess.Popen(cmd)
。
class Server(object):
servers = []
def __init__(self, name, host, port, pipe):
self.name = name.lower()
self.host, self.port = host, port
self.pipe = pipe
@staticmethod
def register(server):
Server.servers.append(server)
@staticmethod
def unregister(server):
Server.servers.remove(server)
def start_waitress(host='0.0.0.0', port=8080):
args = ['--port={}'.format(port),
'--host={}'.format(host), 'yarr.wsgi:application']
return subprocess.Popen(['waitress-serve'] + args)
...
host, port = '0.0.0.0', 8080
Server.register(Server('waitress', host, port, start_waitress()))
...
for server in Server.servers:
if server.name == 'waitress':
server.pipe.terminate()
server.pipe.wait()
Server.unregister(server)
break