2012-09-05 101 views
6

我在OSX Mountain Lion上,試圖使用PID檢索進程的名稱。從PID獲取名稱?

以下是我使用的代碼:

pid_t pid = 10687; 
char pathBuffer [PROC_PIDPATHINFO_MAXSIZE] = ""; 
char nameBuffer [256] = ""; 

int sizeOfVal = sizeof(nameBuffer); 
proc_pidpath(pid, pathBuffer, sizeof(pathBuffer)); 
proc_name(pid, nameBuffer, sizeof(nameBuffer)); 

NSLog(@"Path: %s\n Name: %s\n", pathBuffer, nameBuffer); 

上面的代碼能夠正常檢索名稱,但它只能檢索前15個字符和「忽略」的其餘部分。請注意,這不是顯示名稱的問題,但檢索它。問題不在於我的應用程序的其他部分,因爲我正在獨立應用程序中測試上述代碼。另外請注意,我嘗試更改PID,但不管我嘗試使用哪個PID,代碼僅檢索名稱的前15個字符。路徑檢索完美。

有沒有人有什麼想法我做錯了什麼?

+0

當我研究這個問題,我發現一些更古怪。如果指定的緩衝區長度小於32字節,則即使名稱很短(並且適合31字節緩衝區),也不會有任何內容放入該字符串中。 – charliehorse55

回答

8

函數查看的值是struct proc_bsdshortinfo。它僅限於返回一個16字節的字符串,或者包含空終止符時返回15個可讀字符。

sys/param.h

#define MAXCOMLEN 16  /* max command name remembered */ 

sys/proc_info.h

struct proc_bsdshortinfo { 
     uint32_t    pbsi_pid;  /* process id */ 
     uint32_t    pbsi_ppid;  /* process parent id */ 
     uint32_t    pbsi_pgid;  /* process perp id */ 
    uint32_t    pbsi_status;  /* p_stat value, SZOMB, SRUN, etc */ 
    char     pbsi_comm[MAXCOMLEN]; /* upto 16 characters of process name */ 
    uint32_t    pbsi_flags;    /* 64bit; emulated etc */ 
     uid_t     pbsi_uid;  /* current uid on process */ 
     gid_t     pbsi_gid;  /* current gid on process */ 
     uid_t     pbsi_ruid;  /* current ruid on process */ 
     gid_t     pbsi_rgid;  /* current tgid on process */ 
     uid_t     pbsi_svuid;  /* current svuid on process */ 
     gid_t     pbsi_svgid;  /* current svgid on process */ 
     uint32_t    pbsi_rfu;  /* reserved for future use*/ 
}; 

編輯:爲了解決這個問題,得到的最後一個路徑組件:

pid_t pid = 3051; 
char pathBuffer [PROC_PIDPATHINFO_MAXSIZE]; 
proc_pidpath(pid, pathBuffer, sizeof(pathBuffer)); 

char nameBuffer[256]; 

int position = strlen(pathBuffer); 
while(position >= 0 && pathBuffer[position] != '/') 
{ 
    position--; 
} 

strcpy(nameBuffer, pathBuffer + position + 1); 

printf("path: %s\n\nname:%s\n\n", pathBuffer, nameBuffer); 
+0

謝謝。你有什麼機會知道解決方法嗎? – fdh

+0

獲取完整路徑,然後將字符串修剪到最後一個路徑組件。 – charliehorse55

+0

沒有更優雅的解決方案嗎?考慮到檢索過程信息是許多程序的重要組成部分,應該有一個更有效的接口來檢索這些信息。 – fdh