【Centos】【python】获取进程的PID

获取进程的PID

  1. 查看进程PID的命令是ps -ef | grep 进程名称
    • 问题:在多进程运行时同一个进程名称的pid对应多个pid
    • 解决:根据PPID(父类pid)有无PPID来判断是否是根pid

例如

 ps -ef | grep -v grep| grep -E "Baking|PPID"

输出

UID         PID   PPID  C STIME TTY          TIME CMD
root      69603 275638 86 15:06 pts/0    00:00:06 python Baking.py 1111111
root      69605  69603 89 15:06 pts/0    00:00:06 python Baking.py 1111111
root      69610  69605 87 15:06 pts/0    00:00:06 python Baking.py 1111111
root     275638   2512 88 14:32 pts/0    00:30:21 python Baking.py 1111111

获取进程的pid

def get_process_id(process_name):
    """
    获取进程PID,获取在多进程运行时主pid
    :param process_name: 进程的名称
    :return: 进程的 pid / 多进程的主 pid
    """
    cmd = "ps -ef | grep \\ " + process_name + " | grep -v grep | awk '{print $2\" \"$3}'"
    out = os.popen(cmd)
    pids = out.read().strip('\n')

    pid_map_ppid = {}
    for pid_ppid in pids.split("\n"):
        pid, ppid = pid_ppid.split(' ')
        pid_map_ppid[pid] = ppid

    if not pid_map_ppid:
        return False
    # 判断是否是多进程的主进程
    pid = pid_map_ppid.keys()[0]
    while pid_map_ppid.get(pid_map_ppid.get(pid)):
        pid = pid_map_ppid.get(pid)
    return pid

你可能感兴趣的:(centos,python,linux)