2010-11-24 69 views
0

我有一个python cgi脚本,用于检查进程是否处于活动状态,如果未找到该进程,则启动它。该进程本身是一个网络服务器(基于web.py)。确保该进程正在运行后,我尝试向其发送url请求。这个想法是将这个请求的结果重定向到我的cgi脚本的请求者,基本上我想将查询重定向到侦听不同端口的本地webserver。从cgi脚本中调用urlopen'连接被拒绝'错误

如果我先从服务器启动服务器(findImgServerProcess返回True),则不使用cgi请求,此代码正常工作。但是,如果我尝试通过下面的cgi脚本启动进程,则确实会得到urllib2.urlopen调用,这会引发连接被拒绝的异常。 我不明白为什么? 如果我打印进程列表(在findImgServerProcess()),我可以看到进程在那里,但为什么urllib2.urlopen会抛出异常?我有apache2 webserver设置为使用suexec。

下面的代码:

#!/usr/bin/python 
import cgi, cgitb 
cgitb.enable() 
import os, re 
import sys 
import subprocess 

import urllib2 
urlbase = "http://localhost:8080/getimage" 
imgserver = "/home/martin/public_html/cgi-bin/stlimgservermirror.py" # this is based on web.py 

def findImgServerProcess(): 
    r = subprocess.Popen(["ps", "aux"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] 
    return re.match(".*%s" % os.path.split(imgserver)[-1], r, re.DOTALL) 

def ensureImgServerProcess(): 
    if findImgServerProcess(): 
     return True 

    os.environ['LD_LIBRARY_PATH'] = '/home/martin/lib' 
    fout = open("/dev/null", "w") 
    ferr = fout 
    subprocess.Popen([sys.executable, imgserver], stdout=fout, stderr=subprocess.STDOUT) 
    # now try and find the process 
    return findImgServerProcess() != None 

def main(): 
    if not ensureImgServerProcess(): 
     print "Content-type: text/plain\n" 
     print "image server down!" 
     return 

    form = cgi.FieldStorage() 
    if form.has_key("debug"): 
     print "Content-type: text/plain\n" 
     print os.environ['QUERY_STRING'] 
    else: 
     try: 
      img = urllib2.urlopen("%s?%s" % (urlbase, os.environ['QUERY_STRING'])).read() 
     except Exception, e: 
      print "Content-type: text/plain\n" 
      print e 
      sys.exit() 
     print "Content-type: image/png\n" 
     print img 

if __name__ == "__main__": 
    main() 

回答

0

一种可能性是子进程一直没有机会尝试连接到它之前完全启动。要测试这个,请在​​调用urlopen之前尝试添加time.sleep(5)。

这并不理想,但至少可以帮助您找出问题所在。顺便说一下,您可能想要设置一个更好的方法来检查HTTP守护进程是否正在运行并保持运行。

相关问题