I need to make a function that can kill all processes owned by user and later to start few.
My main problem is that I cannot figure how to check if all processes were killed, and if there are still running processes, to retry for 1-2 times to kill them, and then return error. I want to use only python code.
Here is my code:
import os
import pwd
def pkill(user):
pids = []
user_pids = []
uid = pwd.getpwnam(user).pw_uid
# get all PID
for i in os.listdir('/proc'):
if i.isdigit():
pids.append(i)
# test if PID is owned by user
for i in pids:
puid = os.stat(os.path.join('/proc', i)).st_uid
if puid == uid:
user_pids.append(i)
# print len(user_pids)
# check of PID still exist and kill it
for i in user_pids:
if os.path.exists(os.path.join('/proc',i)):
try:
os.kill(int(i), 15)
except OSError:
Thank you
The default way to check if a process is running, in Linux (it’s POSIX compatible also), is to use
kill -0 PID, so here you can simply do anos.killbut with 0 as a signal, if the process is dead it should throw an exception, if it’s alive it should not.