def send_signal(self, signum):
# if we have a local process, use its method, else determine if the ip is local or remote and issue
# the appropriate version to signal the process.
result = None
if self.local_proc:
if self.pgid > 0 and hasattr(os, "killpg"):
try:
os.killpg(self.pgid, signum)
return result
except OSError:
pass
result = self.local_proc.send_signal(signum)
else:
if self.ip and self.pid > 0:
if BaseProcessProxyABC.ip_is_local(self.ip):
result = self.local_signal(signum)
else:
result = self.remote_signal(signum)
return result
python类killpg()的实例源码
def test_log_follow():
wait_for_service('chronos')
proc = subprocess.Popen(['dcos', 'service', 'log', 'chronos', '--follow'],
preexec_fn=os.setsid,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
time.sleep(10)
proc.poll()
assert proc.returncode is None
os.killpg(os.getpgid(proc.pid), 15)
stdout = proc.stdout.read()
stderr = proc.stderr.read()
print('STDOUT: {}'.format(stdout))
print('STDERR: {}'.format(stderr))
assert len(stdout.decode('utf-8').split('\n')) > 3
def turn_off(self):
"""Turn the media player off."""
import pexpect
if self._pianobar is None:
_LOGGER.info('Pianobar subprocess already stopped')
return
self._pianobar.send('q')
try:
_LOGGER.info('Stopped Pianobar subprocess')
self._pianobar.terminate()
except pexpect.exceptions.TIMEOUT:
# kill the process group
os.killpg(os.getpgid(self._pianobar.pid), signal.SIGTERM)
_LOGGER.info('Killed Pianobar subprocess')
self._pianobar = None
self._player_state = STATE_OFF
self.schedule_update_ha_state()
def _checkpg(pid):
"""
Checks if any members of a process group are alive.
"""
try:
os.killpg(pid, 0)
return True
except OSError:
return False
def close(self):
"""Stops the process controller
Kill the process
"""
self.stop = True
try:
os.killpg(os.getpgid(self.process.pid), signal.SIGTERM)
except ProcessLookupError:
log_debug("Must already be dead")
else:
log_debug("Successfully killed")
ProcessController.instance = None
def keep_writing(self):
"""Input thread method for the process
Sends the user inputs (from InputTranscoder) to the process
"""
while True:
if self.stop:
break
ret = self.process.poll()
if ret is not None:
self.stop = True
readable, writable, executable = select.select([], [self.master], [], 5)
if writable:
try:
(input_type, content) = self.input_transcoder.pop_input(timeout=1)
except Empty:
pass
else:
if input_type == 0:
log_debug("Sending input\n<< {}".format(repr(content)))
data = content.encode('UTF-8')
# data = bytes(chaine, 'iso-8859-15')
while data:
chars_written = os.write(self.master, data)
data = data[chars_written:]
elif input_type == 1:
(signal_type, signal_content) = content
t = fcntl.ioctl(self.master, signal_type, signal_content)
log_debug(struct.unpack('HHHH', t))
elif input_type == 2:
os.killpg(os.getpgid(self.process.pid), content)
log_debug("SENDING SIGNAL TO PROCESS", content)
def tearDown(self):
#os.killpg(self.cloudverifier_process.pid, signal.SIGKILL)
pass
def sigterm_handler(self, signum, frame):
LOG.debug("Signal handler called with signal=%s" % signum)
global SIGTERM_SENT
if not SIGTERM_SENT:
LOG.info("Shutting down %s" % self.name)
SIGTERM_SENT = True
self.stop()
os.killpg(0, signal.SIGTERM)
sys.exit()
def kill(self):
pid = self.process.pid
if sublime.platform() == "windows":
kill_process = subprocess.Popen(['taskkill', '/F', '/T', '/PID', str(pid)], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
kill_process.communicate()
else:
os.killpg(pid, signal.SIGTERM)
ProcessCache.remove(self)
def run(self, inp=None):
name = self.get_obj_file_name()
sandbox = Sandbox()
cmd = self.get_run_command(name, sandbox)
start = timer()
stdout = b''
stderr = b''
env = os.environ.copy()
r = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE,
stderr=subprocess.PIPE,
stdout=subprocess.PIPE, bufsize=4*1024,
cwd=MEDIA_ROOT, preexec_fn=os.setsid,env=env)
try:
if inp is not None:
stdout, stderr = r.communicate(timeout=timeout, input=inp.encode())
else:
stdout, stderr = r.communicate(timeout=timeout)
print('STDOUT : ' + str(stdout, "utf-8"))
print('STDERR : ' + str(stderr, "utf-8"))
except subprocess.TimeoutExpired as e:
print("Timeout expired")
os.killpg(r.pid, signal.SIGINT)
r.returncode = 124
print('Return Code : ' + str(r.returncode))
if self.lang != 'python':
os.remove(MEDIA_ROOT+'/'+name)
print('Elapsed seconds: {:.2f}'.format(timer() - start))
sandbox.delete_sandbox()
return Result(timer() - start, r.returncode, stdout)
def __exit__(self, type_, value, traceback):
print('cleanup: killing group for pid %d' % self.proc.pid)
os.killpg(os.getpgid(self.proc.pid), signal.SIGTERM)
def _reload_services(self, *args, **kwargs):
if self._shutdown.is_set():
# NOTE(sileht): We are in shutdown process no need
# to reload anything
return
# Reset forktimes to respawn services quickly
self._forktimes = []
signal.signal(signal.SIGHUP, signal.SIG_IGN)
os.killpg(0, signal.SIGHUP)
signal.signal(signal.SIGHUP, self._reload_services)
def _fast_exit(self, signo, frame,
reason='Caught SIGINT signal, instantaneous exiting'):
signal.signal(signal.SIGINT, signal.SIG_IGN)
signal.signal(signal.SIGALRM, signal.SIG_IGN)
LOG.info(reason)
os.killpg(0, signal.SIGINT)
os._exit(1)
def kill_udocker_process(process):
logger.info("Stopping udocker container")
# Using SIGKILL instead of SIGTERM to ensure the process finalization
os.killpg(os.getpgid(process.pid), subprocess.signal.SIGKILL)
def make_terminate_handler(process, signal=signal.SIGTERM):
def inner(*args):
try:
os.killpg(os.getpgid(process.pid), signal)
except OSError:
pass
return inner
def shutdown():
if proc:
os.killpg(proc.pid, 2)
for d in [users, tmp, logs, topic]:
if os.path.isdir(d):
shutil.rmtree(d)
def terminate(end, proc, kill):
"""Terminate or kill the process after end."""
if not end or time.time() <= end:
return False
if kill: # Process will not die, kill everything
pgid = os.getpgid(proc.pid)
logging.info(
'Kill %d and process group %d', proc.pid, pgid)
os.killpg(pgid, signal.SIGKILL)
proc.kill()
return True
logging.info(
'Terminate %d on timeout', proc.pid)
proc.terminate()
return True
def _get_new_progress_group_args():
"""
Gets a tuple containing the `preexec_fn` and `creationflags` parameters to subprocess.Popen
required to create a subprocess that can be killed via os.killpg without killing the
process group of the parent process.
"""
preexec_fn = None
creationflags = 0
if not is_jython():
if get_os() == 'windows':
creationflags = subprocess.CREATE_NEW_PROCESS_GROUP
else:
preexec_fn = os.setsid
return preexec_fn, creationflags
def stop(self):
if self.process:
try:
os.killpg(os.getpgid(self.process.pid), signal.SIGTERM)
except OSError:
pass
def close(self):
if self.mpirun_proc is None:
return
if not self._tmpfile.closed:
self._tmpfile.close()
os.killpg(os.getpgid(self.mpirun_proc.pid), signal.SIGTERM)
os.killpg(os.getpgid(self.mpirun_proc.pid), signal.SIGKILL)
self.mpirun_proc.wait()
self.mpirun_proc = None