how to deal with Python BaseHTTPServer killed,but the port is still be occupied?

2024/10/14 1:13:17

I use python BaseHTTPServer,it can handle do_GET,do_POST methods,in do_POST method,i execute linux shell using os.system,when i kill the python script,but the listening port still occupied,so i can't run the script again, the netstat -antp|grep 80 show that the bash/tail is occupied the port 80

import sys
import os
import traceback
import time
import logging.handlers
import logging
from threading import *
from datetime import datetime
import urllib2
reload(sys)
sys.setdefaultencoding('utf-8')class WebRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):server_version = 'python httpserver'sys_version = 'b'backup_dir = Nonedef do_HEAD(s):s.send_response(200)s.send_header("Content-type", "text/html")s.end_headers()def do_GET(self):if self.path == '/foo':self.send_response(200)               os.system('nohup tail -f a.log &')else:self.send_error(404)
if __name__ == "__main__":try:server = BaseHTTPServer.HTTPServer(('',80), WebRequestHandler)    server.serve_forever()except KeyboardInterrupt:server.socket.close()
Answer

File descriptors are inherited by default by child processes, so the socket listening on port 80 is inherited by the command you have launched using your system() call.

To avoid that, you should set the FD_CLOEXEC flag on the listening socket. This can be done by adding (and using) a specific HTTPServer class.

class WebServer(BaseHTTPServer.HTTPServer):def __init__(self, *args, **kwargs):BaseHTTPServer.HTTPServer.__init__(self, *args, **kwargs)# Set FD_CLOEXEC flagflags = fcntl.fcntl(self.socket.fileno(), fcntl.F_GETFD)flags |= fcntl.FD_CLOEXECfcntl.fcntl(self.socket.fileno(), fcntl.F_SETFD, flags)

Related :

  • Process started from system command in C inherits parent fd's
https://en.xdnf.cn/q/118012.html

Related Q&A

Circular imports and class fields in python3

Okay, I do understand that this topic is old as hell, but I couldnt find an answer to the particular question that I am asking.Lets say that we have a very simple structure: two files, a.py and b.py, t…

Bad HTTP response returned from the server. Code 500

I have a problem to use pywinrm on linux, to get a PowerShell Session. I read several posts and questions on sites about that. But any that can solve my question. The error is in the Kerberos autenti…

Iterate one list of synsets over another

I have two sets of wordnet synsets (contained in two separate list objects, s1 and s2), from which I want to find the maximum path similarity score for each synset in s1 onto s2 with the length of outp…

Flask werkzeug.routing.BuildError

I doing a flask app and when i try to put a link to redirect a user to his profile page by callingBuildError: Could not build url for endpoint profile. Did you forgetto specify values [business_name]?…

getting attribute of an element with its corresponding Id

suppose that i have this xml file :<article-set xmlns:ns0="http://casfwcewf.xsd" format-version="5"> <article><article id="11234"><source><hostn…

How to install selenium python on Mac

Ive downloaded the Selenium zip file for python and it contains the folder with the setup.py. It says on python.org that I have to type in terminal python setup.py install but it gives me this error th…

aws s3 - object has no attribute server_side_encryption

Can someone please explain the differences in these two calls. The first one gives the correct server_side_encryption and the second one gives an error. The other attributes give the same value-#!/usr/…

Removing nested for loop to find coincidence values

I am currently using a nested for loop to iterate through to arrays to find values that match a certain criterion. The problem is that this method is incredibly inefficient and time consuming. I was to…

Combine two pandas DataFrame into one new

I have two Pandas DataFrames whose data from different sources, but both DataFrames have the same column names. When combined only one column will keep the name.Like this:speed_df = pd.DataFrame.from_d…

Reasons of slowness in numpy.dot() function and how to mitigate them if custom classes are used?

I am profiling a numpy dot product call. numpy.dot(pseudo,pseudo)pseudo is a numpy array of custom objects. Defined as:pseudo = numpy.array([[PseudoBinary(1), PseudoBinary(0), PseudoBinary(1)],[PseudoB…