<s> __author__ = '<STR_LIT>' <EOL> import sys , os , atexit <EOL> from signal import SIGTERM <EOL> class Daemon ( object ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , pidfile , stdin = '<STR_LIT>' , stdout = '<STR_LIT>' , stderr = '<STR_LIT>' ) : <EOL> self . stdin = stdin <EOL> self . stdout = stdout <EOL> self . stderr = stderr <EOL> self . pidfile = pidfile <EOL> def daemonize ( self ) : <EOL> """<STR_LIT>""" <EOL> try : <EOL> pid = os . fork ( ) <EOL> if pid > <NUM_LIT:0> : <EOL> sys . exit ( <NUM_LIT:0> ) <EOL> except OSError , e : <EOL> sys . stderr . write ( "<STR_LIT>" % ( e . errno , e . strerror ) ) <EOL> sys . exit ( <NUM_LIT:1> ) <EOL> os . chdir ( "<STR_LIT:/>" ) <EOL> os . setsid ( ) <EOL> os . umask ( <NUM_LIT:0> ) <EOL> try : <EOL> pid = os . fork ( ) <EOL> if pid > <NUM_LIT:0> : <EOL> sys . exit ( <NUM_LIT:0> ) <EOL> except OSError , e : <EOL> sys . stderr . write ( "<STR_LIT>" % ( e . errno , e . strerror ) ) <EOL> sys . exit ( <NUM_LIT:1> ) <EOL> sys . stdout . flush ( ) <EOL> sys . stderr . flush ( ) <EOL> si = file ( self . stdin , '<STR_LIT:r>' ) <EOL> so = file ( self . stdout , '<STR_LIT>' ) <EOL> se = file ( self . stderr , '<STR_LIT>' , <NUM_LIT:0> ) <EOL> os . dup2 ( si . fileno ( ) , sys . stdin . fileno ( ) ) <EOL> os . dup2 ( so . fileno ( ) , sys . stdout . fileno ( ) ) <EOL> os . dup2 ( se . fileno ( ) , sys . stderr . fileno ( ) ) <EOL> atexit . register ( self . delpid ) <EOL> pid = str ( os . getpid ( ) ) <EOL> file ( self . pidfile , '<STR_LIT>' ) . write ( "<STR_LIT>" % pid ) <EOL> def delpid ( self ) : <EOL> os . remove ( self . pidfile ) <EOL> def start ( self , * args ) : <EOL> """<STR_LIT>""" <EOL> try : <EOL> pf = file ( self . pidfile , '<STR_LIT:r>' ) <EOL> pid = int ( pf . read ( ) . strip ( ) ) <EOL> pf . close ( ) <EOL> except IOError : <EOL> pid = None <EOL> if pid : <EOL> message = "<STR_LIT>" <EOL> sys . stderr . write ( message % self . pidfile ) <EOL> sys . exit ( <NUM_LIT:1> ) <EOL> self . daemonize ( ) <EOL> self . run ( * args ) <EOL> def stop ( self ) : <EOL> """<STR_LIT>""" <EOL> try : <EOL> pf = file ( self . pidfile , '<STR_LIT:r>' ) <EOL> pid = int ( pf . read ( ) . strip ( ) ) <EOL> pf . close ( ) <EOL> except IOError : <EOL> pid = None <EOL> if not pid : <EOL> message = "<STR_LIT>" <EOL> sys . stderr . write ( message % self . pidfile ) <EOL> return <EOL> try : <EOL> os . kill ( pid , SIGTERM ) <EOL> except OSError , err : <EOL> err = str ( err ) <EOL> if err . find ( "<STR_LIT>" ) > <NUM_LIT:0> : <EOL> if os . path . exists ( self . pidfile ) : <EOL> os . remove ( self . pidfile ) <EOL> else : <EOL> print str ( err ) <EOL> sys . exit ( <NUM_LIT:1> ) <EOL> def restart ( self ) : <EOL> """<STR_LIT>""" <EOL> self . stop ( ) <EOL> self . start ( ) <EOL> def run ( self , * args ) : <EOL> """<STR_LIT>""" </s>
