我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用psutil.NoSuchProcess()。
def pids_active(pids_computer): """ This function find pids of computer and return the valid. """ pid_valid = {} for pid in pids_computer: data = None try: process = psutil.Process(pid) data = {"pid": process.pid, "status": process.status(), "percent_cpu_used": process.cpu_percent(interval=0.0), "percent_memory_used": process.memory_percent()} except (psutil.ZombieProcess, psutil.AccessDenied, psutil.NoSuchProcess): data = None if data is not None: pid_valid[process.name()] = data return pid_valid
def on_ask_user_allow_or_deny(self, evt): try: exe = evt.process.exe() cmdline = evt.process.cmdline() except (psutil.NoSuchProcess, psutil.AccessDenied): logger.warn('Ransomware process is caught, but the process does ' 'not exist (PID: %d)' % evt.pid) logger.critical('\033[91m') logger.critical('*** [Crypto ransom detected] ***') logger.critical('[PID]: %d' % evt.process.pid) logger.critical('[EXE]: %r' % exe) logger.critical('[Command]: %r' % cmdline) logger.critical('[File]: %s' % evt.path) logger.critical('********************************\033[0m') flush_stdin() yes_no = raw_input('> Block it? (Y/n) ') allow = 'n' in yes_no.lower() if allow: event.EventUserAllowProcess(evt.process).fire() else: event.EventUserDenyProcess(evt.process).fire()
def test_procfs_path(self): tdir = tempfile.mkdtemp() try: psutil.PROCFS_PATH = tdir self.assertRaises(IOError, psutil.virtual_memory) self.assertRaises(IOError, psutil.cpu_times) self.assertRaises(IOError, psutil.cpu_times, percpu=True) self.assertRaises(IOError, psutil.boot_time) # self.assertRaises(IOError, psutil.pids) self.assertRaises(IOError, psutil.net_connections) self.assertRaises(IOError, psutil.net_io_counters) self.assertRaises(IOError, psutil.net_if_stats) self.assertRaises(IOError, psutil.disk_io_counters) self.assertRaises(IOError, psutil.disk_partitions) self.assertRaises(psutil.NoSuchProcess, psutil.Process) finally: psutil.PROCFS_PATH = "/proc" os.rmdir(tdir)
def find_server_processes(cls, port=None): result = [] for p in psutil.process_iter(): try: if isinstance(type(p).cmdline, property): pname = p.name cmdline = p.cmdline else: pname = p.name() cmdline = p.cmdline() if pname == 'adb': if 'fork-server' in cmdline and 'server' in cmdline: if port != None and str(port) not in cmdline: continue result.append(p) except psutil.NoSuchProcess: continue return result
def join(pid, timeout): if pid == 0: return start = time.time() while time.time() - start < timeout: try: proc = Process(pid) except NoSuchProcess: return except IOError, e: if e.errno == errno.ESRCH: return else: raise e time.sleep(0.5) raise Timeout('timeout')
def get_cmdlines(): """Retrieve the cmdline of each process running on the system.""" processes = [] # Get our current PID as well as the parent so we can exclude them. current_pid = os.getpid() parent_pid = os.getppid() for proc in psutil.process_iter(): try: if proc.pid not in [current_pid, parent_pid]: processes.append(' '.join(proc.cmdline())) except psutil.NoSuchProcess: pass return processes
def kill (chdir, procname = None, include_children = True, signaling = True): import psutil for i in range (2): pid = status (chdir, procname) if not pid: break if signaling: os.kill (pid, signal.SIGTERM) time.sleep (2) if include_children: try: killtree.kill (pid, True) except psutil.NoSuchProcess: pass while processutil.is_running (pid, procname): time.sleep (1) try: os.remove (os.path.join (chdir, ".pid")) except FileNotFoundError: pass
def cpu_times(self): ''' return {pid: {'user': 0.0, 'sys': 0.0}}, chrome_reset ''' chrome_procs = self.get_chrome_procs() new_pids = {p.pid for p in chrome_procs} old_pids = {pid for pid in self.last_cpu_times} try: cpu_times = {p.pid: p.cpu_times() for p in chrome_procs} except psutil.NoSuchProcess: # Chrome restarted since fetching the new pids above. Better luck next time. return {}, True if new_pids != old_pids: # We don't know when the Chrome procs were restarted, so don't # return elapsed time until next run. self.last_cpu_times = cpu_times return {}, True # Same chrome pids as last run: measure the elapsed cpu times ordered_old_times = (self.last_cpu_times[p.pid] for p in chrome_procs) ordered_new_times = (cpu_times[p.pid] for p in chrome_procs) cpu_times_diff = {p.pid: {'user': (t[0] - l[0]) / self.interval, 'sys': (t[1] - l[1]) / self.interval} for (p, t, l) in zip(chrome_procs, ordered_new_times, ordered_old_times)} self.last_cpu_times = cpu_times return cpu_times_diff, False
def on_crypto_ransom(self, evt): logger.debug('Whitelist: %s' % json.dumps(self.whitelist, indent=4)) logger.debug('Suspended: %s' % json.dumps([ {'pid': p.pid, 'exe': p.exe()} for p in self.suspended ], indent=4)) if any(suspended.pid == evt.pid for suspended in self.suspended): return # ignore captured ransom events try: p = psutil.Process(evt.pid) cmdline = p.cmdline() except (psutil.NoSuchProcess, psutil.AccessDenied): logger.warn('Suspicious process %d exited before being caught' % evt.pid) return if cmdline not in self.whitelist: p.suspend() self.suspended.append(p) event.EventAskUserAllowOrDeny(p, evt.path).fire() else: logger.info('Allowed white-listed process: %d' % evt.pid)
def get_absolute_path(event_raw): ''' Keeps a cache of processes' cwds, in case that their events might come after they're terminated. ''' pid = event_raw.get('pid') path = event_raw.get('path') if path and path[0] == '/': return os.path.realpath(path) cwd = None logger.debug('%r' % pid_cwd) try: process = psutil.Process(pid) cwd = process.cwd() pid_cwd[pid] = cwd # cache every pid's cwd except (psutil.NoSuchProcess, psutil.AccessDenied): cwd = pid_cwd.get(pid) if not cwd: return None return os.path.realpath(os.path.join(cwd, path))
def on_crypto_ransom(self, evt): logger.debug('Got crypto ransom event') cmdline, exe = None, None try: p = psutil.Process(evt.pid) cmdline = p.cmdline() exe = p.exe() except (psutil.NoSuchProcess, psutil.AccessDenied): pid_profile = self.engine.pid_profiles.get(evt.pid) if pid_profile is not None: cmdline = pid_profile.get('cmdline') exe = cmdline[0] if cmdline else None crypto_ransom_event = { 'pid': evt.pid, 'path': evt.path, 'cmdline': cmdline, 'exe': exe, 'timestamp': datetime.datetime.now().isoformat() } self.web.ctx['events'].append(crypto_ransom_event) self.web.socketio.emit('event', crypto_ransom_event)
def check(proc, target_name, max_timeout): """ Check CPU usage of target process """ try: pid = proc.pid start_time = time() if psutil.Process(pid).children(): for child in psutil.Process(pid).children(): if child.name() == target_name: while True: cpu = all(0 == child.cpu_percent(interval=0.1) for x in xrange(8)) if cpu is not None and cpu is True: kill(proc, child.pid) break if max_timeout is not None or max_timeout != 0: end_time = time() elapsed = end_time - start_time if elapsed > max_timeout: kill(proc, child.pid) break except psutil.NoSuchProcess: pass
def check_phantomjs_process(self): """ Check if phantomjs is running. :return: """ # Check rss and restart if too large, then check existence # http://stackoverflow.com/questions/568271/how-to-check-if-there-exists-a-process-with-a-given-pid-in-python try: if not hasattr(self,'driver'): self.open_driver() pid, rss_mb = self.phantomjs_pid_and_memory() if rss_mb > self.phantomjs_rss_limit_mb: # memory limit self.quit_driver(pid=pid) self.open_driver() pid, _ = self.phantomjs_pid_and_memory() # check existence os.kill(pid, 0) except (OSError,psutil.NoSuchProcess,Exception) as e: if self.debug: print('.phantomjs_pid_and_memory() exception:\n{}'.format(e)) if issubclass(type(e),psutil.NoSuchProcess): raise Exception("There's a phantomjs zombie, and the thread shouldn't have reached this statement.") return False else: return True
def phantomjs_pid_and_memory(self): """ Return the pid and memory (MB) of the phantomjs process, restart if it's a zombie, and exit if a restart isn't working after three attempts. """ for k in range(3): # three strikes try: @self.phantomjs_short_timeout def phantomjs_process_pid(): return self.driver.service.process.pid pid = phantomjs_process_pid() rss_mb = psutil.Process(pid).memory_info().rss / float(2 ** 20) break except (psutil.NoSuchProcess,Exception) as e: if self.debug: print('.service.process.pid exception:\n{}'.format(e)) self.quit_driver(pid=pid) self.open_driver() else: # throw in the towel and exit if no viable phantomjs process after multiple attempts print('No viable phantomjs process after multiple attempts!') sys.exit(1) return (pid, rss_mb)
def kill_using_shell(logger, pid, signal=signal.SIGTERM): try: process = psutil.Process(pid) # Use sudo only when necessary - consider SubDagOperator and SequentialExecutor case. if process.username() != getpass.getuser(): args = ["sudo", "kill", "-{}".format(int(signal)), str(pid)] else: args = ["kill", "-{}".format(int(signal)), str(pid)] # PID may not exist and return a non-zero error code logger.error(subprocess.check_output(args, close_fds=True)) logger.info("Killed process {} with signal {}".format(pid, signal)) return True except psutil.NoSuchProcess as e: logger.warning("Process {} no longer exists".format(pid)) return False except subprocess.CalledProcessError as e: logger.warning("Failed to kill process {} with signal {}. Output: {}" .format(pid, signal, e.output)) return False
def pid(self, process_name): """ process_name: System Process Name return: Process name's pid, integer """ for proc in psutil.process_iter(): try: pinfo = proc.as_dict(attrs=['pid', 'name']) p_name = pinfo['name'] p_pid = pinfo['pid'] if process_name == p_name: return p_pid except psutil.NoSuchProcess: pass
def terminate_process_and_children(self, name): """ Recursively terminate all children of respective process @args: name: Name of the job """ if name not in self.jobs: print("[%s] does not exist as a process!", name) ppid = self.jobs[name]['process'].pid try: parent_proc = psutil.Process(ppid) except psutil.NoSuchProcess: return children = parent_proc.children(recursive=True) for proc in children: l.debug(proc) try: proc.send_signal(signal.SIGKILL) except: pass
def test_process_iter(self): self.assertIn(os.getpid(), [x.pid for x in psutil.process_iter()]) sproc = get_test_subprocess() self.assertIn(sproc.pid, [x.pid for x in psutil.process_iter()]) p = psutil.Process(sproc.pid) p.kill() p.wait() self.assertNotIn(sproc.pid, [x.pid for x in psutil.process_iter()]) with mock.patch('psutil.Process', side_effect=psutil.NoSuchProcess(os.getpid())): self.assertEqual(list(psutil.process_iter()), []) with mock.patch('psutil.Process', side_effect=psutil.AccessDenied(os.getpid())): with self.assertRaises(psutil.AccessDenied): list(psutil.process_iter())
def test_race_condition(self, mock_get_utility, mock_process, mock_net): # This tests a race condition, or permission problem, or OS # incompatibility in which, for some reason, no process name can be # found to match the identified listening PID. from psutil._common import sconn conns = [ sconn(fd=-1, family=2, type=1, laddr=("0.0.0.0", 30), raddr=(), status="LISTEN", pid=None), sconn(fd=3, family=2, type=1, laddr=("192.168.5.10", 32783), raddr=("20.40.60.80", 22), status="ESTABLISHED", pid=1234), sconn(fd=-1, family=10, type=1, laddr=("::1", 54321), raddr=("::1", 111), status="CLOSE_WAIT", pid=None), sconn(fd=3, family=2, type=1, laddr=("0.0.0.0", 17), raddr=(), status="LISTEN", pid=4416)] mock_net.return_value = conns mock_process.side_effect = psutil.NoSuchProcess("No such PID") # We simulate being unable to find the process name of PID 4416, # which results in returning False. self.assertFalse(self._call(17)) self.assertEqual(mock_get_utility.generic_notification.call_count, 0) mock_process.assert_called_once_with(4416)
def TOR_PROC_CHECK(): isTorRunnin = False TOR_INFO = {} TOR_PROC = None for proc in psutil.process_iter(): try: pinfo = proc.as_dict(attrs=['pid', 'name']) except psutil.NoSuchProcess: pass else: if pinfo['name'] == "tor": isTorRunnin = True TOR_INFO['pid'] = pinfo['pid'] TOR_INFO['name'] = pinfo['name'] break if isTorRunnin == True: print ("[" + Fore.GREEN + Style.BRIGHT + "+" + Style.RESET_ALL + "]" + Fore.GREEN + Style.BRIGHT + " Tor is running." + Style.RESET_ALL) TOR_PROC = psutil.Process(int(TOR_INFO['pid'])) return TOR_PROC else: print ("[" + Fore.RED + Style.BRIGHT + "-" + Style.RESET_ALL + "]" + Fore.RED + Style.BRIGHT + " Tor is not running." + Style.RESET_ALL) exit()
def stop(hcitool, hcidump): # import psutil here so as long as all implementations are in the same file, all will work import psutil log.info('Stop receiving broadcasts') def kill_child_processes(parent_pid): try: parent = psutil.Process(parent_pid) except psutil.NoSuchProcess: return for process in parent.children(recursive=True): subprocess.call(['sudo', '-n', 'kill', '-s', 'SIGINT', str(process.pid)]) kill_child_processes(hcitool.pid) subprocess.call(['sudo', '-n', 'kill', '-s', 'SIGINT', str(hcitool.pid)]) kill_child_processes(hcidump.pid) subprocess.call(['sudo', '-n', 'kill', '-s', 'SIGINT', str(hcidump.pid)])
def status(): """ Fetch service status :return: """ if master_pid("c") is True: print colored(" SERVICE IS RUNNING... ", "white", "on_blue") h = PrettyTable([u"??ID", u"????"]) h.align[u"??ID"] = "l" h.align[u"????"] = "l" h.padding_width = 1 pid_list = processors_list("r") for pid in pid_list: try: if psutil.Process(pid).is_running(): h.add_row([pid, colored("RUNNING...",attrs=["bold"])]) else: h.add_row([colored(pid, "magenta", "on_yellow", attrs=["bold"]), colored("STOPED", "magenta", "on_yellow", attrs=["bold"])]) except psutil.NoSuchProcess: h.add_row([colored(pid, "yellow", attrs=["bold", "blink"]), colored("LOSTED", "red", attrs=["bold", "blink"])]) print h else: cmsg("SERVICE IS STOPED!", "e")
def start(): old_pid=get_pid() try: process=psutil.Process(pid=old_pid) except psutil.NoSuchProcess as e : process=None os.system("rm -rf %s/pid/crondeamon.pid"%datadir) if old_pid and process: cmd_line=process.cmdline() mask=0 for j in cmd_line: if "twistd" in j or "crondeamon" in j : mask+=1 if mask>=2: print "server is running ! " else: os.system("mkdir -p %s/pid"%datadir) os.system("mkdir -p %s/log"%datadir) os.system("twistd --pidfile %s/pid/crondeamon.pid --logfile %s/log/crondeamon.log crondeamon"%(datadir,datadir)) print "start success!" else: os.system("mkdir -p %s/pid"%datadir) os.system("mkdir -p %s/log"%datadir) os.system("twistd --pidfile %s/pid/crondeamon.pid --logfile %s/log/crondeamon.log crondeamon"%(datadir,datadir)) print "start success!"
def start(self): if self.process or self.is_running(): self.logger.error('Server already running call close_server first') return if len(self.arguments) == 0: self.logger.info('Launching server and waiting for child processes') else: self.logger.info('Launching server and waiting for child processes with extra arguments, %s' % self.arguments) try: process = subprocess.Popen([self.path, '-log', self.arguments]) process = psutil.Process(process.pid) self.attach(process) except subprocess.CalledProcessError as ex: self.logger.exception('Server failed to start... %s' % ex) return False except psutil.NoSuchProcess as ex: self.logger.exception('Server started but crashed shortly after... %s' % ex) return False self.logger.info('Server running successfully') return True
def show_prism_info(queues, raw, by_queue, queue_class, worker_class): show_queues(queues, raw, by_queue, queue_class, worker_class) if not raw: click.echo('') show_workers(queues, raw, by_queue, queue_class, worker_class) show_cluster_info() click.echo('') click.echo("Redis clients: %i" % len(redis_conn.client_list())) click.echo("Local blobs: %i" % len(os.listdir(os.path.expandvars(BLOB_DIR)))) try: click.echo("Open files: %i" % len(server_proc.open_files())) except psutil.NoSuchProcess: sys.exit(0) if not raw: click.echo('') import datetime click.echo('Updated: %s' % datetime.datetime.now())
def check_process_exists_and_amqp_connected(name): processes = filter(lambda p: check_process_name(name, p), psutil.process_iter()) if not processes: critical("%s is not running" % name) for p in processes: try: connections = p.get_connections(kind='inet') except psutil.NoSuchProcess: continue found_amqp = ( len(list(itertools.takewhile(lambda c: len(c.remote_address) <= 1 or c.remote_address[1] != AMQP_PORT, connections))) != len(connections)) if found_amqp: ok("%s is working." % name) critical("%s is not connected to AMQP" % name)
def run(self): with open(os.devnull, 'w') as devnull: try: # If the service is disabled in Preferences # the query returns a non-zero error # should use this query better in future if subprocess.check_call(['launchctl', 'print', 'system/com.openssh.sshd'], stdout=devnull, stderr=devnull): return (True, "disabled") else: return (False, "enabled in Sharing Prefs: Remote Login") except subprocess.CalledProcessError as e: # this only gets run if sshd isn't enabled by # launchd as checked above pids = [] for p in psutil.process_iter(): try: if p.name() == 'sshd': pids.append(p.pid) except psutil.NoSuchProcess: pass if len(pids): return (False, "enabled manually - see pids: {} ".format(', '.join([str(p) for p in pids]))) else: return (True, "disabled")
def run(self): """ Run the check. All check scripts must implement this method. It must return a tuple of: (<success>, <message>) In this example, if the check succeeds and FileSharing processes are nowhere to be found, the check will return (True, "No FileSharing processes found"). If the check fails and an FileSharing process is found, it returns (False, "Found SMB or AFP FileSharing processes with pids <pids>") """ pids = [] for p in psutil.process_iter(): try: if (p.name() == 'AppleFileServer' or p.name() == 'smbd'): pids.append(p.pid) except psutil.NoSuchProcess: pass if len(pids): return (False, "found SMB or AFP file sharing processes with pids: {} - Disable Sharing Prefs: File Sharing".format(', '.join([str(p) for p in pids]))) else: return (True, "disabled")
def pause_pipeline(self, run_id, user): """ Interrupt pipeline by sending signal to corresponding worker's children """ pid = self.pids.get(run_id) if pid: pretty_print("Pausing pipeline: id=%d, user=%s" % (run_id, user)) try: parent = psutil.Process(pid) children = parent.children(recursive=True) for child in children: run_as(cmd=['kill', child.pid], user=user) except psutil.NoSuchProcess: pretty_print("Error pausing pipeline: no process with ID %d" % int(pid)) else: pretty_print("Error pausing pipeline: ID %d not found" % run_id)
def KillAllAdb(): def GetAllAdb(): for p in psutil.process_iter(): try: if 'adb' in p.name: yield p except (psutil.NoSuchProcess, psutil.AccessDenied): pass for sig in [signal.SIGTERM, signal.SIGQUIT, signal.SIGKILL]: for p in GetAllAdb(): try: logging.info('kill %d %d (%s [%s])', sig, p.pid, p.name, ' '.join(p.cmdline)) p.send_signal(sig) except (psutil.NoSuchProcess, psutil.AccessDenied): pass for p in GetAllAdb(): try: logging.error('Unable to kill %d (%s [%s])', p.pid, p.name, ' '.join(p.cmdline)) except (psutil.NoSuchProcess, psutil.AccessDenied): pass
def get_used_files(): """Get files used by processes with name scanpy.""" import psutil loop_over_scanpy_processes = (proc for proc in psutil.process_iter() if proc.name() == 'scanpy') filenames = [] for proc in loop_over_scanpy_processes: try: flist = proc.open_files() for nt in flist: filenames.append(nt.path) # This catches a race condition where a process ends # before we can examine its files except psutil.NoSuchProcess as err: pass return set(filenames)
def kill_proc(procname): done = False for proc in psutil.process_iter(): process = psutil.Process(proc.pid) if process.name() == procname: try: process.terminate() process.wait(timeout=3) done = True except psutil.AccessDenied: print "Error: Access Denied to terminate %s" % procname except psutil.NoSuchProcess: pass except psutil.TimeoutExpired: if proz['killcount'] == 2: print "Error: Terminating of %s failed! (tried 3 times)" % procname else: print "Error: Terminating of %s took to long.. retrying" % procname proz['killcount'] += 1 kill_proc(procname) break if done: print "%s terminated!" % procname
def check_cpu(self): while True: try: if self.pid is None: time.sleep(0.2) continue proc = psutil.Process(self.pid) cpu = 0 l = [] for x in xrange(20): tmp = int(proc.cpu_percent(interval=0.1)) cpu += tmp l.append(tmp) if cpu is not None and (cpu <= 100 or l.count(0) > 10): log("CPU at 0%, killing") self.cpu_killed = True self.do_kill() break else: time.sleep(0.5) except psutil.NoSuchProcess: break
def all_running_processes_for_case(self, _filter): procs = [] for p in psutil.process_iter(): try: if psutil.pid_exists(p.pid): if _filter in p.cwd(): procs.append({"run": p.cwd() + " " + p.name(),"cmd":p.cmdline()}) except (psutil.AccessDenied): pass except (psutil.NoSuchProcess): pass return procs ## # Function to kill all running processes for one case # @param _filter search filter <string> # @retval list of all killed processes <list>
def kill_all_running_processes_for_case(self, _filter): procs = [] for p in psutil.process_iter(): try: if psutil.pid_exists(p.pid): if _filter in p.cwd(): procs.append({"run": p.cwd() + " " + p.name()}) self.kill_proc_tree(p.pid) except (psutil.AccessDenied): pass except (psutil.NoSuchProcess): pass return procs ## # Function to retrieve all processes for one case (running and completed) # @param _case case <string> # @retval list of all processes <list>
def _check_virtualbox(): """ Check if VirtualBox is running. VirtualBox conflicts with S2E's requirement for KVM, so VirtualBox must *not* be running together with S2E. """ # Adapted from https://github.com/giampaolo/psutil/issues/132#issuecomment-44017679 # to avoid race conditions for proc in psutil.process_iter(): try: if proc.name == 'VBoxHeadless': raise CommandError('S2E uses KVM to build images. VirtualBox ' 'is currently running, which is not ' 'compatible with KVM. Please close all ' 'VirtualBox VMs and try again') except NoSuchProcess: pass
def kill(pid): ''' Kill a pid ''' process = psutil.Process(pid) try: for proc in process.children(recursive=True) + [process]: try: log.info("Killing pid={0}".format(proc.pid)) proc.kill() time.sleep(0.1) proc.terminate() except psutil.NoSuchProcess as exc: log.error(exc) except AttributeError: log.info("Killing pid={0}".format(process.pid)) process.kill() time.sleep(0.1) try: proc.terminate() except UnboundLocalError: pass
def __running(): """ Check if SafeEyes is already running. """ process_count = 0 for proc in psutil.process_iter(): if not proc.cmdline: continue try: # Check if safeeyes is in process arguments if callable(proc.cmdline): # Latest psutil has cmdline function cmd_line = proc.cmdline() else: # In older versions cmdline was a list object cmd_line = proc.cmdline if ('python3' in cmd_line[0] or 'python' in cmd_line[0]) and ('safeeyes' in cmd_line[1] or 'safeeyes' in cmd_line): process_count += 1 if process_count > 1: return True # Ignore if process does not exist or does not have command line args except (IndexError, psutil.NoSuchProcess): pass return False
def kill_windows_cassandra_procs(): # On Windows, forcefully terminate any leftover previously running cassandra processes. This is a temporary # workaround until we can determine the cause of intermittent hung-open tests and file-handles. if is_win(): try: import psutil for proc in psutil.process_iter(): try: pinfo = proc.as_dict(attrs=['pid', 'name', 'cmdline']) except psutil.NoSuchProcess: pass else: if (pinfo['name'] == 'java.exe' and '-Dcassandra' in pinfo['cmdline']): print 'Found running cassandra process with pid: ' + str(pinfo['pid']) + '. Killing.' psutil.Process(pinfo['pid']).kill() except ImportError: debug("WARN: psutil not installed. Cannot detect and kill " "running cassandra processes - you may see cascading dtest failures.")
def poll(interval): # sleep some time time.sleep(interval) procs = [] procs_status = {} for p in psutil.process_iter(): try: p.dict = p.as_dict(['username', 'nice', 'memory_info', 'memory_percent', 'cpu_percent', 'cpu_times', 'name', 'status']) try: procs_status[p.dict['status']] += 1 except KeyError: procs_status[p.dict['status']] = 1 except psutil.NoSuchProcess: pass else: procs.append(p) # return processes sorted by CPU percent usage processes = sorted(procs, key=lambda p: p.dict['cpu_percent'], reverse=True) return (processes, procs_status)
def PidIsRunning(pid): """ Check if a process with PID pid is running. """ try: proc = psutil.Process(int(pid)) if proc.status == psutil.STATUS_DEAD: return False if proc.status == psutil.STATUS_ZOMBIE: return False return True # Assume other status are valid except psutil.NoSuchProcess: return False
def ownhandle() : my_regex = r".*" + re.escape(sys.argv[1]) + r".*" regex = re.compile(my_regex, re.IGNORECASE) for proc in psutil.process_iter(): try: pinfo = proc.as_dict(attrs=['pid']) except psutil.NoSuchProcess: pass else: #print pinfo['pid'] try: proci = psutil.Process(pinfo['pid']) for files in proci.open_files() : #print files #handles = re.match(my_regex, files, re.IGNORECASE) match = regex.search(str(files)) #print match if match is not None and pinfo['pid'] not in safepids : return(pinfo['pid']) except : pass
def t5(pretty, factory): pipe = Pipe() p = P2(pipe) p.start() factory.processes.append(p) gc_pid = pipe.get() try: proc = psutil.Process(gc_pid) except Exception, e: print('FAIL %s: could not query grandchild: %s' % (pretty, e)) return False os.kill(p.pid, signal.SIGKILL) ok = False for i in range(3): try: proc = psutil.Process(gc_pid) except psutil.NoSuchProcess: ok = True break time.sleep(0.5) if not ok: print('FAIL %s: could query grandchild: %s' % (pretty, proc)) return False return True # grandchild does not die when child dies if PDEATHSIG is unset?