#!/usr/bin/env python2.6 import os, signal, sys, time from resource import setrlimit, RLIMIT_AS configs = {} quitnow = False judgehome = os.path.abspath(os.path.dirname(sys.argv[0])) def main(): os.chdir(judgehome) # redirect stdout and stderr to file os.close(1) fd = os.open('log/daemon.log', os.O_WRONLY | os.O_APPEND | os.O_CREAT) os.close(2) fd = os.dup(fd) # setup resource usage setrlimit(RLIMIT_AS, (1024 * 1024 * 256, 1024 * 1024 * 256)) # setup signal handler signal.signal(signal.SIGINT, quit) signal.signal(signal.SIGQUIT, quit) # find config files files = os.listdir(os.path.join(judgehome, 'conf')) for filename in files: if filename[:5] == 'conf-' and filename[-3:] == '.py': configs[filename] = 0 # start all the judge process for conf in configs.keys(): configs[conf] = run(conf) # check for the dead of judge process while not quitnow: for conf in configs.keys(): pid = configs[conf] ret = os.waitpid(pid, os.WNOHANG) if ret[0]: print >>sys.stderr, 'judge process %d dead, restarting...' % pid configs[conf] = run(conf) time.sleep(1) def run(conf): pid = os.fork() if pid: return pid else: cmd = '/usr/bin/python' conf = os.path.join('conf', conf) os.execvp(cmd, (cmd, 'judge', conf)) def quit(sig, frame): quitnow = True for conf in configs.keys(): pid = configs[conf] os.kill(pid, sig) for conf in configs.keys(): pid = configs[conf] os.waitpid(pid, 0) exit() if __name__ == '__main__': main()