2017-09-06 56 views
0

我想獲取os x系統中進程信息的快照。我如何通過編程的方式獲取os x中的所有進程名?不僅僅是應用程序進程

'NSProcessInfo'只能獲取調用進程的信息。

PS CMD可以是一個解決方案,但我想要一個C或Objective-C程序。

+0

我已經通過libc方法「proc_listallpids」&&「proc_pidpath」得到了解決方案。 – shaoheng

+0

注意:'proc_name'只能獲取應用程序的進程名稱,其他進程名稱(如daemon)將不會被獲取。 – shaoheng

回答

0

下面是一個使用libproc.h遍歷系統上所有進程並確定它們有多少屬於進程的有效用戶的示例。您可以根據自己的需要輕鬆修改。

- (NSUInteger)maxSystemProcs 
{ 
    int32_t maxproc; 
    size_t len = sizeof(maxproc); 
    sysctlbyname("kern.maxproc", &maxproc, &len, NULL, 0); 

    return (NSUInteger)maxproc; 
} 

- (NSUInteger)runningUserProcs 
{ 
    NSUInteger maxSystemProcs = self.maxSystemProcs; 

    pid_t * const pids = calloc(maxSystemProcs, sizeof(pid_t)); 
    NSAssert(pids, @"Memory allocation failure."); 

    const int pidcount = proc_listallpids(pids, (int)(maxSystemProcs * sizeof(pid_t))); 

    NSUInteger userPids = 0; 
    uid_t uid = geteuid(); 
    for (int *pidp = pids; *pidp; pidp++) { 
     struct proc_bsdshortinfo bsdshortinfo; 
     int writtenSize; 

     writtenSize = proc_pidinfo(*pidp, PROC_PIDT_SHORTBSDINFO, 0, &bsdshortinfo, sizeof(bsdshortinfo)); 

     if (writtenSize != (int)sizeof(bsdshortinfo)) { 
      continue; 
     } 

     if (bsdshortinfo.pbsi_uid == uid) { 
      userPids++; 
     } 
    } 

    free(pids); 
    return (NSUInteger)userPids; 
} 
相關問題