停止生成的进程继承绑定端口

时间:2015-03-19 18:13:30

标签: python macos bash subprocess port

我正在编写一个根据请求生成VLC实例的小型HTTP服务器。 但是,如果我在启动的VLC实例仍在运行时停止我的服务器并尝试重新启动它,则会因error: [Errno 48] Address already in use

而失败

服务器:

class Handler(BaseHTTPRequestHandler):
    def do_GET(self):
        vlcPort = 8191
        linkArg = "example.mp4"
        os.system('~/scripts/backVlcNoBorder.sh --http-port %s %s'%(vlcPort,linkArg))

class ThreadingHTTPServer(ThreadingMixIn, HTTPServer):
    def server_bind(self):
        print "self.allow_reuse_address",self.allow_reuse_address
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.socket.bind(self.server_address)
        # HTTPServer.server_bind(self)

if __name__ == "__main__":
    server = ThreadingHTTPServer(("localhost",1111), Handler)
    server.serve_forever()

它调用启动VLC的脚本(〜/ scripts / backVlcNoBorder.sh)

#!/bin/bash
nohup /Applications/VLC.app/Contents/MacOS/VLC $@ >/dev/null 2>/dev/null &

如果我向服务器发出请求,VLC会启动。 如果我然后关闭服务器而不是VLC,并尝试重新启动服务器,它将失败:

self.allow_reuse_address 1
Exception in thread Thread-1:
Traceback (most recent call last):
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 810, in __bootstrap_inner
    self.run()
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 763, in run
    self.__target(*self.__args, **self.__kwargs)
  File "./http_request_server.py", line 263, in serve_on_port
    server = ThreadingHTTPServer(("localhost",1111), Handler)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/SocketServer.py", line 420, in __init__
    self.server_bind()
  File "./http_request_server.py", line 256, in server_bind
    self.socket.bind(self.server_address)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/socket.py", line 224, in meth
    return getattr(self._sock,name)(*args)
error: [Errno 48] Address already in use

之后我跑了lsof -n -i4TCP:1111 | grep LISTEN看看仍然绑定到1111

bash    24365 admin    3u  IPv4 0x6d73e857a76dcad5      0t0  TCP 127.0.0.1:lmsocialserver (LISTEN)
VLC     24366 admin    3u  IPv4 0x6d73e857a76dcad5      0t0  TCP 127.0.0.1:lmsocialserver (LISTEN)

我不知道为什么bash和VLC都在听1111,我想这可能与使用os.system的{​​{1}}有关吗?​​

如何在不必关闭VLC的情况下重新启动服务器,或者如何阻止VLC加入绑定端口?

操作系统是Mac OSX 10.9

1 个答案:

答案 0 :(得分:0)

有两个问题:

  1. 使用subprocess并通过close_fds=True来修复第一个;如果除了http服务器进程之外的某些进程保持fd打开
  2. 将服务器配置为使用SO_REUSEADDRits analog on your system,如果重新启动速度过快(TIME_WAIT状态)。