Gav*_*Roy 10 python daemon basehttpserver
我正在研究一个需要嵌入HTTP服务器的守护进程.我正在尝试使用BaseHTTPServer,当我在前台运行它时,它工作正常,但是当我尝试将守护进程分叉到后台时,它会停止工作.我的主要应用程序继续工作,但BaseHTTPServer没有.
我相信这与BaseHTTPServer将日志数据发送到STDOUT和STDERR这一事实有关.我正在将它们重定向到文件.这是代码片段:
# Start the HTTP Server
server = HTTPServer((config['HTTPServer']['listen'],config['HTTPServer']['port']),HTTPHandler)
# Fork our process to detach if not told to stay in foreground
if options.foreground is False:
try:
pid = os.fork()
if pid > 0:
logging.info('Parent process ending.')
sys.exit(0)
except OSError, e:
sys.stderr.write("Could not fork: %d (%s)\n" % (e.errno, e.strerror))
sys.exit(1)
# Second fork to put into daemon mode
try:
pid = os.fork()
if pid > 0:
# exit from second parent, print eventual PID before
print 'Daemon has started - PID # %d.' % pid
logging.info('Child forked as PID # %d' % pid)
sys.exit(0)
except OSError, e:
sys.stderr.write("Could not fork: %d (%s)\n" % (e.errno, e.strerror))
sys.exit(1)
logging.debug('After child fork')
# Detach from parent environment
os.chdir('/')
os.setsid()
os.umask(0)
# Close stdin
sys.stdin.close()
# Redirect stdout, stderr
sys.stdout = open('http_access.log', 'w')
sys.stderr = open('http_errors.log', 'w')
# Main Thread Object for Stats
threads = []
logging.debug('Kicking off threads')
while ...
lots of code here
...
server.serve_forever()
Run Code Online (Sandbox Code Playgroud)
我在这里做错了什么,或者BaseHTTPServer以某种方式阻止成为守护进程?
编辑:更新代码以演示额外的,以前缺少的代码流,并且log.debug显示在我的分叉后台后台守护程序中,我在fork之后遇到代码.
经过一段谷歌搜索后,我终于偶然发现了这个BaseHTTPServer文档,之后我最终得到了:
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from SocketServer import ThreadingMixIn
class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
"""Handle requests in a separate thread."""
server = ThreadedHTTPServer((config['HTTPServer']['listen'],config['HTTPServer']['port']), HTTPHandler)
server.serve_forever()
Run Code Online (Sandbox Code Playgroud)
在我分叉并最终解决我的问题之后,大部分都出现了.
| 归档时间: |
|
| 查看次数: |
15534 次 |
| 最近记录: |