Subprocess. Popen () must be added with close_fds = True

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.