tests/killdaemons.py
changeset 1130 193e68a0c8d2
parent 1128 7f09e7ac63a7
child 1329 10d0d9d5c0f0
equal deleted inserted replaced
1122:feb663195388 1130:193e68a0c8d2
       
     1 #!/usr/bin/env python
       
     2 
       
     3 import os, sys, time, errno, signal
       
     4 
       
     5 if os.name =='nt':
       
     6     import ctypes
       
     7     def kill(pid, logfn, tryhard=True):
       
     8         logfn('# Killing daemon process %d' % pid)
       
     9         PROCESS_TERMINATE = 1
       
    10         handle = ctypes.windll.kernel32.OpenProcess(
       
    11                 PROCESS_TERMINATE, False, pid)
       
    12         ctypes.windll.kernel32.TerminateProcess(handle, -1)
       
    13         ctypes.windll.kernel32.CloseHandle(handle)
       
    14 else:
       
    15     def kill(pid, logfn, tryhard=True):
       
    16         try:
       
    17             os.kill(pid, 0)
       
    18             logfn('# Killing daemon process %d' % pid)
       
    19             os.kill(pid, signal.SIGTERM)
       
    20             if tryhard:
       
    21                 for i in range(10):
       
    22                     time.sleep(0.05)
       
    23                     os.kill(pid, 0)
       
    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 
       
    33 def killdaemons(pidfile, tryhard=True, remove=False, logfn=None):
       
    34     if not logfn:
       
    35         logfn = lambda s: s
       
    36     # Kill off any leftover daemon processes
       
    37     try:
       
    38         fp = open(pidfile)
       
    39         for line in fp:
       
    40             try:
       
    41                 pid = int(line)
       
    42             except ValueError:
       
    43                 continue
       
    44             kill(pid, logfn, tryhard)
       
    45         fp.close()
       
    46         if remove:
       
    47             os.unlink(pidfile)
       
    48     except IOError:
       
    49         pass
       
    50 
       
    51 if __name__ == '__main__':
       
    52     path, = sys.argv[1:]
       
    53     killdaemons(path)
       
    54