def kill_cmd(self):
if self.cmd_pid > 1:
try:
os.close(self.cmd_fd)
except OSError, e:
if e.errno == errno.EBADF:
pass # already closed
else:
raise e
try:
os.kill(self.cmd_pid, signal.SIGKILL)
os.waitpid(self.cmd_pid, 0)
except OSError, e:
if e.errno not in [errno.ECHILD, errno.ESRCH]:
raise Exception('unhandled errno: %d' % e.errno)
self.cmd_pid = -1
python类kill()的实例源码
def kill_cmd(self):
if self.cmd_pid > 1:
try:
os.close(self.cmd_fd)
except OSError, e:
if e.errno == errno.EBADF:
pass # already closed
else:
raise e
try:
os.kill(self.cmd_pid, signal.SIGKILL)
os.waitpid(self.cmd_pid, 0)
except OSError, e:
if e.errno not in [errno.ECHILD, errno.ESRCH]:
raise Exception('unhandled errno: %d' % e.errno)
self.cmd_pid = -1
def _kill_ssh(self):
if self.ssh_pid > 1:
try:
os.kill(self.ssh_pid, signal.SIGTERM)
os.waitpid(self.ssh_pid, 0)
except OSError, e:
if e.errno not in [errno.ECHILD, errno.ESRCH]:
raise Exception('unhandled errno: %d' % e.errno)
self.self_pid = -1
try:
os.close(self.ssh_fd)
except OSError, e:
if e.errno == errno.EBADF:
pass # already closed
else:
print 'WHAT?', e
raise e
def t01(factory):
pretty = '%s t1' % __file__
print(pretty)
ctrl = factory.make_master('master')
pid = ctrl.get_pid()
os.kill(pid, signal.SIGUSR1)
try:
pid = ctrl.get_pid()
except ConnectionClosed, e:
print('FAIL %s: SIGUSR1 killed the process: %s' % (pretty, e))
return False
except Exception, e:
print('FAIL %s: unknown error: %s' % (pretty, e))
return False
return True
# check that trace files are written to <home>/.ave/hickup with predictable
# file names
def t04(factory):
pretty = '%s t4' % __file__
print(pretty)
ctrl = factory.make_master('master')
bpid = ctrl.get_pid()
spids = ctrl.get_session_pids()
if [pid for pid in spids if pid < 2] != []:
print('FAIL %s: impossible session PIDs: %d' % (pretty, spids))
return False
# signal the broker and wait for the hickup directory to appear. the signal
# should be propagated to the equipment lister long before the directory is
# created.
os.kill(bpid, signal.SIGUSR1)
path = os.path.join(factory.HOME.path, '.ave', 'hickup')
wait_hickup_dir(path, 3)
spids2 = ctrl.get_session_pids()
if spids2 != spids:
print('FAIL %s: sessions affected: %s != %s' % (pretty, spids2, spids))
return False
return True
def terminate(self):
try:
os.kill(self.pid, signal.SIGTERM)
except OSError, e:
if e.errno == errno.ESRCH:
return # process already killed by someone else
if e.errno == errno.EPERM:
# this can only happen if the original session was started as
# a different user. e.g. if the broker has been restarted with
# --demote=<some other user>. but don't worry too much about it
# as sessions are eventually terminated anyway.
print(
'WARNING: session with PID=%d not terminated because it '
'is owned by a different user. did you restart a broker '
'as a different user?' % self.pid
)
return
raise e
def __call__(self, fn):
def decorated(*args, **kwargs):
pretty = '%s %s' % (fn.func_code.co_filename, fn.func_name)
print(pretty)
self.HOME = Workspace()
self.processes = []
os.makedirs(os.path.join(self.HOME.path, '.ave','config'))
try:
result = fn(pretty, self, *args, **kwargs)
except:
raise
finally:
self.kill()
self.HOME.delete()
return result
return decorated
def t4():
pretty = '%s t4' % __file__
print(pretty)
pid, fd = ave.cmd.run_bg('echo hello')
poller = select.poll()
poller.register(fd, select.POLLIN)
events = poller.poll(1000) # milliseconds
tmp = ''
for e in events:
if not (e[1] & select.POLLIN):
print('FAIL %s: unexpected poll event: %d' % (pretty, e[1]))
os.kill(pid, signal.SIGKILL)
tmp += os.read(fd, 1024)
if not tmp.startswith('hello'):
print('FAIL %s: wrong result: "%s"' % (pretty, tmp))
os.kill(pid, signal.SIGKILL)
os.waitpid(pid, 0)
return True
# check that return value from executed program is correct
def t01(pretty, factory):
ctrl = factory.make_control(home=factory.HOME.path)
pid = ctrl.get_pid()
os.kill(pid, signal.SIGUSR1)
try:
pid = ctrl.get_pid()
except ConnectionClosed, e:
print('FAIL %s: SIGUSR1 killed the process: %s' % (pretty, e))
return False
except Exception, e:
print('FAIL %s: unknown error: %s' % (pretty, e))
return False
return True
# check that trace files are written to <home>/.ave/hickup with predictable
# file names
def t03(pretty, factory):
ctrl = factory.make_control(home=factory.HOME.path)
pid = ctrl.get_pid()
ctrl.make_child()
os.kill(pid, signal.SIGUSR1)
path = os.path.join(factory.HOME.path, '.ave', 'hickup')
wait_hickup_dir(path, 3)
files = glob.glob(os.path.join(path, '*'))
if len(files) != 2:
print('FAIL %s: wrong number of files: %s' % (pretty, files))
return False
return True
# check that the signal is not propagated to non-ave processes such as external
# tools. these will otherwise terminate if they do not handle the signal.
def t10():
pretty = '%s t10' % __file__
print(pretty)
s,p = find_free_port()
q = Pipe()
c = MockControl(p, None, s, [], q)
c.start()
r = RemoteControl(('',p), None, timeout=5)
r.sync_ping()
c.terminate()
try:
q.get(timeout=1)
except Exception, e:
print('FAIL %s: never got oob message: %s' % (pretty, str(e)))
c.kill()
return False
c.join(2)
return True
# check that two contollers with connections to each other discover when the
# other one shuts down
def _process_exists(pid):
"""Check if a process with PID ``pid`` exists.
:param pid: PID to check
:type pid: ``int``
:returns: ``True`` if process exists, else ``False``
:rtype: ``Boolean``
"""
try:
os.kill(pid, 0)
except OSError: # not running
return False
return True
def stop(self):
"""
Stop the daemon
"""
# Get the pid from the pidfile
try:
pf = file(self.pidfile,'r')
pid = int(pf.read().strip())
pf.close()
except IOError:
pid = None
if not pid:
message = "pidfile %s does not exist. Daemon not running?\n"
sys.stderr.write(message % self.pidfile)
return # not an error in a restart
# Try killing the daemon process
try:
while 1:
os.kill(pid, SIGTERM)
time.sleep(0.1)
except OSError, err:
err = str(err)
if err.find("No such process") > 0:
if os.path.exists(self.pidfile):
os.remove(self.pidfile)
else:
print str(err)
sys.exit(1)
def stop(self):
"""
Stop the daemon
"""
# Get the pid from the pidfile
try:
pf = file(self.pidfile,'r')
pid = int(pf.read().strip())
pf.close()
except IOError:
pid = None
if not pid:
message = "pidfile %s does not exist. Daemon not running?\n"
sys.stderr.write(message % self.pidfile)
return # not an error in a restart
# Try killing the daemon process
try:
while 1:
os.kill(pid, SIGTERM)
time.sleep(0.1)
except OSError, err:
err = str(err)
if err.find("No such process") > 0:
if os.path.exists(self.pidfile):
os.remove(self.pidfile)
else:
print str(err)
sys.exit(1)
def close(self):
self._stop()
if self.process is not None:
os.kill(self.process.pid, 15)
self.process.wait()
self.process = None
def stop(self):
try:
pf = file(self.pidfile,'r')
pid = int(pf.read().strip())
pf.close()
except IOError:
pid = None
if not pid:
message = "pidfile %s does not exist. Daemon not running?\n"
sys.stderr.write(message % self.pidfile)
return # not an error in a restart
print("killing process with pid {0}".format(pid))
try:
while 1:
os.kill(pid, SIGTERM)
time.sleep(0.1)
except OSError, err:
err = str(err)
if err.find("No such process") > 0:
if os.path.exists(self.pidfile):
os.remove(self.pidfile)
else:
print str(err)
sys.exit(1)
def stop(self):
os.kill(self.writer_proc.pid, signal.SIGINT)
def terminate(self):
# Assuming stop() was already called, the reader and writer should have
# already exited
self.writer_proc.kill()
self.reader_proc.kill()
self.writer_proc.wait()
self.reader_proc.wait()
def query_commandAlive(self):
if self._pid != None:
try:
os.kill(self._pid, 0)
if os.waitpid(self._pid, os.WNOHANG) == (0,0):
return True
else:
return False
except OSError:
pass
return False
def query_commandAlive(self):
if self._pid != None:
try:
os.kill(self._pid, 0)
if os.waitpid(self._pid, os.WNOHANG) == (0,0):
return True
else:
return False
except OSError:
pass
return False