2016-04-26 40 views
4

我正在Python中創建一個簡單的程序,應該保存我當前的進程(使用linux和pycharm)。看不到一些進程名稱

我的類代碼:

class pidSaver: 
    __pidDictionary={} 
    def __init__(self): 
     pids = [pid for pid in os.listdir('/proc') if pid.isdigit()] 
     for pid in pids: 
      try: 
       os.kill(int(pid), 0) 
      except OSError as e: 
       if e.errno != errno.EPERM: #no premission error 
        continue 
      try: 
       self.__pidDictionary[pid]=open(os.path.join('/proc', pid, 'cmdline'), 'rb').read() 
      except IOError: # proc has already terminated 
       continue 

    def getDic(self): 
     return self.__pidDictionary 

,我的主要代碼:

pidsTry = pidSaver() 
printList= pidsTry.getDic() 
keyList= list(printList.keys()) 
IntegerKeyList=[] 
for key in keyList: 
    IntegerKeyList.append(int(key)) 
IntegerKeyList.sort() 
for key in IntegerKeyList: 
    print "%d : %s" %(key ,printList[str(key)]) 

輸出:

1 : /sbin/init 
2 : 
3 : 
5 : 
... 
7543 : less 
... 

所以從某些原因,一些過程中,我不能的得到一個名字,我得到了一個空白。 當我在我的電腦上運行命令ps -aux | less我得到了這樣的結果:

root   1 0.0 0.0 33776 4256 ?  Ss אפר24 0:01 /sbin/init 
root   2 0.0 0.0  0  0 ?  S אפר24 0:00 [kthreadd] 
root   3 0.0 0.0  0  0 ?  S אפר24 0:00 [ksoftirqd/0] 
myUser  7543 0.0 0.0 13752 1548 pts/9 T אפר24 0:00 less 

所以基本上,我不能在我的Python看到的過程是由「[]」所包圍的過程。

我不明白這是爲什麼。另外,我也想得到它們。我該怎麼做,爲什麼會這樣呢?

謝謝!

+0

很確定'cat/proc/2/cmdline'也會告訴你什麼都沒有,試着運行'strace ps -aux | grep/proc' –

+0

@PadraicCunningham你是對的。但是這是一個pid 2的過程。也許我弄錯了?有更好的方式向我顯示信息?我不明白這是爲什麼?爲什麼'cat/proc/1/cmdline'給我提供信息,但是2沒有? – moshem

+0

如果你看看strace輸出,你可以看到'/ status'等等。這是名字來自你沒有看到的地方。 –

回答

2

你無法看到的這些進程是內核線程。正如名稱所說,它們在內核空間中運行,因此不是PID 1的子節點,即init系統。他們的cmdline是空的,因爲他們沒有任何相應的可執行文件被調用,並且沒有參數被傳遞,而這個空cmdline是識別它們的一種非常安全的方法。如果你仍然想獲得他們的名字,那麼在名稱字段下的文件/proc /「pid」/ status