Today, I am working on a web page to control the memcached restart function. I thought it was very simple. I didn't get the pid, and then kill it. It's just that simple to restart memcached.
I did not expect to use subprocess. Popen () to call the command. I found that response was indeed returned to the client, but the http connection between the server and the client was still connected.
Looked at the python documentation and found: http://docs.python.org/library/subprocess.html
Popen2 closes all file descriptors by default, but you have to specify
Close_fds = TrueWithPopen
My code is as follows:
Def _ restart (port, start_cmd ):
Cmd = 'ps aux | grep "memcached. * % s" '% port
P = subprocess. Popen (cmd, shell = True, close_fds = True, # close_fds = True must be added; otherwise, the sub-process will always exist.
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
Hope to use __^ for you