2016-05-22 21 views
-2

Ich habe ein Python-Programm. Es speichert eine Variable namens "pid" mit einer bestimmten PID eines Prozesses. Zuerst muss ich überprüfen, dass der Prozess, der diese PID-Nummer besitzt, wirklich der Prozess ist, nach dem ich suche, und wenn es so ist, muss ich ihn von Python löschen. Also zuerst muss ich irgendwie nachsehen, dass der Name des Prozesses zum Beispiel "ffinder" ist und wenn es ein finder ist, dann töt es. Ich muss eine alte Version von Python verwenden, damit ich psutil und subprocess nicht verwenden kann. Gibt es einen anderen Weg, dies zu tun?Holen Sie sich den Prozessnamen von pid

+0

'os.system ("killall PFINDER")' – alexis

+0

möglich Duplikat http://stackoverflow.com/questions/4189717/get-process-name-by-pid – Tanu

+0

os.system funktioniert nicht, weil es alle Prozesse mit diesem Namen beendet, nicht nur die, die getötet werden müssen. –

Antwort

1

Sie können diese Information direkt vom /proc Dateisystem erhalten, wenn Sie keine separate Bibliothek wie psutil verwenden möchten.

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. 
Verwandte Themen