tests/killdaemons.py
branchstable
changeset 1126 dbcb11553a3b
parent 1125 20a680e7f09f
child 1127 79d7aa832cf4
equal deleted inserted replaced
1125:20a680e7f09f 1126:dbcb11553a3b
     1 #!/usr/bin/env python
     1 #!/usr/bin/env python
     2 
     2 
     3 import os, time, errno, signal
     3 import os, time, errno, signal
     4 
     4 
     5 # Kill off any leftover daemon processes
     5 def killdaemons(pidfile, tryhard=True, remove=False, logfn=None):
     6 try:
     6     if not logfn:
     7     fp = open(os.environ['DAEMON_PIDS'])
     7         logfn = lambda s: s
     8     for line in fp:
     8     # Kill off any leftover daemon processes
     9         try:
     9     try:
    10             pid = int(line)
    10         fp = open(pidfile)
    11         except ValueError:
    11         for line in fp:
    12             continue
    12             try:
    13         try:
    13                 pid = int(line)
    14             os.kill(pid, 0)
    14             except ValueError:
    15             os.kill(pid, signal.SIGTERM)
    15                 continue
    16             for i in range(10):
    16             try:
    17                 time.sleep(0.05)
       
    18                 os.kill(pid, 0)
    17                 os.kill(pid, 0)
    19             os.kill(pid, signal.SIGKILL)
    18                 logfn('# Killing daemon process %d' % pid)
    20         except OSError, err:
    19                 os.kill(pid, signal.SIGTERM)
    21             if err.errno != errno.ESRCH:
    20                 if tryhard:
    22                 raise
    21                     for i in range(10):
    23     fp.close()
    22                         time.sleep(0.05)
    24 except IOError:
    23                         os.kill(pid, 0)
    25     pass
    24                 else:
       
    25                     time.sleep(0.1)
       
    26                     os.kill(pid, 0)
       
    27                 logfn('# Daemon process %d is stuck - really killing it' % pid)
       
    28                 os.kill(pid, signal.SIGKILL)
       
    29             except OSError, err:
       
    30                 if err.errno != errno.ESRCH:
       
    31                     raise
       
    32         fp.close()
       
    33         if remove:
       
    34             os.unlink(pidfile)
       
    35     except IOError:
       
    36         pass
       
    37 
       
    38 if __name__ == '__main__':
       
    39     killdaemons(os.environ['DAEMON_PIDS'])
       
    40