简体   繁体   English

Python杀死用户拥有的所有进程

[英]Python kill all processes owned by user

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. 我的主要问题是我无法弄清楚如何检查所有进程是否都被杀死,以及是否仍有正在运行的进程,请重试1-2次以杀死它们,然后返回错误。 I want to use only python code. 我只想使用python代码。

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 谢谢

can't you do the same thing you did to find the processes? 您不能做与找到流程相同的事情吗? that function should return 0.. 该函数应返回0。

在Linux(也与POSIX兼容)中,检查进程是否正在运行的默认方法是使用kill -0 PID ,因此,如果进程已死,您可以在此处简单地执行os.kill但将0作为信号它应该引发异常,如果它还活着,则不应。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM