通过pid获取进程名称

时间:2016-05-22 18:26:53

标签: python linux

我有一个python程序。它存储一个名为“pid”的变量,其中包含进程的给定pid。首先,我需要检查拥有此pid号的进程是否正是我正在寻找的进程,如果是,我需要从python中删除它。所以首先我需要检查过程的名称是例如“pfinder”,如果它是pfinder而不是杀死它。我需要使用旧版本的python,所以我不能使用psutil和subprocess。还有其他办法吗?

1 个答案:

答案 0 :(得分:1)

如果您不想使用psutil这样的单独库,则可以直接从/proc文件系统获取此信息。

import os
import signal

pid = '123'
name = 'pfinder'

pid_path = os.path.join('/proc', pid)
if os.path.exists(pid_path):
    with open(os.join(pid_path, 'comm')) as f:
        content = f.read().rstrip('\n')

    if name == content:
         os.kill(pid, signal.SIGTERM) 
   /proc/[pid]/comm (since Linux 2.6.33)
          This file exposes the process's comm value—that is, the
          command name associated with the process.  Different threads
          in the same process may have different comm values, accessible
          via /proc/[pid]/task/[tid]/comm.  A thread may modify its comm
          value, or that of any of other thread in the same thread group
          (see the discussion of CLONE_THREAD in clone(2)), by writing
          to the file /proc/self/task/[tid]/comm.  Strings longer than
          TASK_COMM_LEN (16) characters are silently truncated.

          This file provides a superset of the prctl(2) PR_SET_NAME and
          PR_GET_NAME operations, and is employed by
          pthread_setname_np(3) when used to rename threads other than
          the caller.