Hii,
I hope whoever reading are doing well ,
I have got a query , like , mine is windows machine , and installed kali to experiment and whenever I open few tabs , the memory will shoot up to 98 percent(other applications added) and system stops responding and then as a solution I got an idea that , I can simply kill processes , whenever system resources reaches 90 percent and , I have written script using some sources , and excluded the root users processes and I am stilll unsure , if this will trouble my system , so anyone ,can please read the code and let me know , if I can execute this as job , when ever the memory consumption goes above 90 percent this gets executed and kill the least recent cache.
Thanks
I hope whoever reading are doing well ,
I have got a query , like , mine is windows machine , and installed kali to experiment and whenever I open few tabs , the memory will shoot up to 98 percent(other applications added) and system stops responding and then as a solution I got an idea that , I can simply kill processes , whenever system resources reaches 90 percent and , I have written script using some sources , and excluded the root users processes and I am stilll unsure , if this will trouble my system , so anyone ,can please read the code and let me know , if I can execute this as job , when ever the memory consumption goes above 90 percent this gets executed and kill the least recent cache.
Code:
import psutil
import os
import time
import signal
IGNORE_USERS = ["root"]
MEMORY_THRESHOLD = 90.0
def get_external_process():
external_procs = []
for proc in psutil.process_iter(['pid','name','username','memory_percent']):
try:
if proc.info['username'] not in IGNORE_USERS:
external_procs.append(proc)
except (psutil.NoSuchProcess,psutil.AccessDenied):
continue
return external_procs
while True:
mem = psutil.virtual_memory()
if mem.percent >= MEMORY_THRESHOLD:
print(f" High memory usage detected:{mem.percent}%")
processes = get_external_processes()
processes.sort(key = lambda p:p.info['memory_percent'] reverse = True)
for proc in processes:
try:
print(f"killing PID {proc.pid}({proc.name()}) using proc.info['memory_percent']:.2f}% RAM")
os.kill(proc.pid,signal.SIGKILL)
break
except Exception as e:
print("Error:" ,e)
time.sleep(5)
Thanks

