今天在做一个web页面控制memcached重启的功能,本以为非常简单,不就获取pid,然后kill,在重新启动memcached就这么简单。
没想到使用subprocess.Popen() 来调用命令时竟然发现response确实是返回到客户端了,但是服务器端和客户端的http连接竟然还连接着,一直不断。
查看了一下python的文档,发现:http://docs.python.org/library/subprocess.html
popen2 closes all file descriptors by default, but you have to specify close_fds=True with Popen
我的代码如下:
def _restart(port, start_cmd):
cmd = 'ps aux | grep "memcached .* %s"' % port
p = subprocess.Popen(cmd, shell=True, close_fds=True, # 必须加上close_fds=True,否则子进程会一直存在
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdoutdata, stderrdata = p.communicate()
if p.returncode != 0:
return False, error_response(cmd, stderrdata)
for r in stdoutdata.split('\n'):
if cmd in r:
continue
break
if r:
pid = r.split()[1]
cmd = 'kill %s' % pid
p = subprocess.Popen(cmd, shell=True, close_fds=True,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p.communicate()
p = subprocess.Popen(start_cmd, shell=True, close_fds=True,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdoutdata, stderrdata = p.communicate()
if p.returncode != 0:
return False, error_response(cmd, stderrdata)
return True, None
希望对你有用 ^_^