Tibor Balogh Tibor Balogh - 6 months ago 50
Linux Question

Get the process name by pid

I have a python program. It stores a variable called "pid" with a given pid of a process. First of all I need to check that the process which owns this pid number is really the process I'm looking for and if it is I need to kill it from python. So first I need to check somehow that the name of the process is for example "pfinder" and if it is pfinder than kill it. I need to use an old version of python so I can't use psutil and subprocess. Is there any other way to do this?

Answer

You can directly obtain this information from the /proc file system if you don't want to use a separate library like psutil.

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.