4

I have this script in python on linux which deploys vnc locally, does some graphical job on this vnc screen, and kills vnc. Sometimes after the job is done process named gnome-panel hangs and stays with 100% cpu usage. Then I need to log in through putty and kill all those processes manually (sometime lots of them actually). I would like to add few lines to my python script when it finishes its job, which will not only kill vnc (it does it already), but also kill gnome-panel if it consumes certain amount of cpu over given time period. I cant simply kill all gnome-panels, as some of them are working fine (im deploying 4 vnc screens at the same time).

So I need this condition in python:

if process name is gnome-panel and consumes over 80% of cpu and runs over 1 minute, kill process id

thank you!

orsz
  • 78
  • 1
  • 7
  • For "consumes over 80% of cpu and runs over 1 minute" you mean that the process was started more than one minute ago and in this moment consumes more than 80% cpu, or that *during the last minute* it *always* used more than 80% cpu? – Bakuriu Aug 27 '13 at 10:16
  • "the process was started more than one minute ago and in this moment consumes more than 80% cpu" this is correct, thx – orsz Aug 27 '13 at 11:11

4 Answers4

2

You can use the psutil library to obtain the cpu percent of processes and eventually kill them. This library works with python from 2.4 to 3.3(and PyPy), on Linux, Windows, Solaris, FreeBSD and OS X both 32 and 64 bit.

The following(untested) code should do what you want:

gnome_panel_procs = []
for process in psutil.process_iter():
    # I assume the gnome-panel processes correctly set their name
    # eventually you could use process.cmdline instead
    if process.name == 'gnome-panel':
        gnome_panel_procs.append(process)

for proc in gnome_panel_procs:
    for _ in range(60):
        # check cpu percentage over 1 second
        if proc.get_cpu_percent(1) < 80 or not proc.is_running():
            # less than 80% of cpu or process terminated
            break
    else:
        # process used 80% of cpu for over 1 minute
        proc.kill()

Note: calling is_running() prevents issues with pid reuse, which could happen in the other solutions proposed(even though with really small chance).


If you want to check whether the process was started more than one minute ago, and in this moment uses more than 80% CPU, then something simpler can be used:

import time
import psutil

for proc in psutil.process_iter():
    if proc.name == 'gnome-panel' and time.time() - proc.create_time > 1:
        if proc.get_cpu_percent() > 80:
            proc.kill()

This will kill any gnome-panel process, even though it didn't use much CPU during the last minute, but only in the last few seconds.

Bakuriu
  • 98,325
  • 22
  • 197
  • 231
  • this should be what I need, let me test it – orsz Aug 27 '13 at 11:20
  • I cant test it. I cant add psutil module due some kind of errors. I have installed python-devel and trying easy_install but it doesnt work. psutil/_psutil_linux.c: In function ‘init_psutil_linux’: psutil/_psutil_linux.c:418: error: ‘RLIMIT_RTTIME’ undeclared (first use in this function) – orsz Aug 27 '13 at 15:54
  • @orsz Strange. I've never had problems installing it. If you are on ubuntu you can install it using the package manager(search for `python-psutil` or `python3-psutil`). You could try installing it from the sources(it's a matter of unpacking and launching `python setup.py install`, eventually using `sudo`). – Bakuriu Aug 27 '13 at 17:11
  • Im on centos, but yum install python-psutil helped :) and it probably works as expected, as I cant see zombie processes - problem solved, thank you – orsz Aug 27 '13 at 19:34
1
import os

os.system(' ps aux| grep gnome-panel | awk \'{if($3>80) print $2}\' |xargs kill -9 ') 
laalto
  • 150,114
  • 66
  • 286
  • 303
Reegan Miranda
  • 2,879
  • 6
  • 43
  • 55
0

ps aux | grep 'gnome-panel ' | awk '{if ($3>80)print $2}' | xargs kill -9

zhanglong
  • 1
  • 1
  • and it needs to take time into consideration – orsz Aug 27 '13 at 09:00
  • this might be the answer if I would like to use cron jobs (lets try it). could you please add TIME consideration (process must work longer than 1 minut) to this condition? ps aux | grep 'gnome-panel ' | awk '{if ($3>80)print $2}' | xargs kill -9 – orsz Aug 27 '13 at 15:52
0

Looks like this was already implemented here to get the results of ps aux

ps = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE).communicate()[0]
processes = ps.split('\n')
# this specifies the number of splits, so the splitted lines
# will have (nfields+1) elements
nfields = len(processes[0].split()) - 1
processes = [row.split(None, nfields) for row in processes[1:]]

An example process is:

['greg', '6359', '0.0', '0.1', '16956', '8868', 'pts/3', 'S+', '01:40', '0:00', 'python']

Then you can finish by looping over all the processes

for process in processes:
    if "gnome-terminal" in process[-1] \
        and float(process[2]) > 0.8 \
            and int(process[-2].split(":")[-1]) > 1: 
        subprocess.call(["kill", "-9", process[0]])

I'm sure there's a less hacky way to do this though

Community
  • 1
  • 1
Greg
  • 5,422
  • 1
  • 27
  • 32
  • does it also take time into consideration? – orsz Aug 27 '13 at 08:44
  • How do you want time taken into consideration? – Greg Aug 27 '13 at 09:01
  • o ok i see what you mean – Greg Aug 27 '13 at 09:17
  • Reading the question I don't think your last check on the time is correct. You shouldn't check whether the process was started more than one minute ago and its CPU percentage, but whether the process, during the last minute, always used more than 80% cpu. And in order to this you must call `ps aux` with a certain interval for one minute. – Bakuriu Aug 27 '13 at 10:15
  • Im certain that if the process is still there after 1 minute and still using more than 80% during check its the process I want to terminate. I want this code snippet to be the easiest and fastest solution. I can run some cpu usage monitor or something, but it is still consuming too much resources. Its easier to just run it once (while for instance starting or closing my vncs) and see if cpu >80% time >1min. Correct me if im wrong.... – orsz Aug 27 '13 at 11:17