2017-09-06 7 views
0

os x 시스템에서 프로세스 정보의 스냅 샷을 가져오고 싶습니다.os x에서 모든 프로세스 이름을 프로그래밍 방식으로 얻을 수 있습니까? 응용 프로그램 프로세스가 아닙니다.

'NSProcessInfo'는 호출 프로세스의 정보 만 가져올 수 있습니다.

ps cmd는 하나의 해결책 일 수 있지만 c 또는 objective-c 프로그램을 원합니다.

+0

저는 libc 메소드 "proc_listallpids"&& "proc_pidpath"로 해결책을 얻었습니다. – shaoheng

+0

알림 : 'proc_name'은 앱 프로그램의 프로세스 이름 만 가져올 수 있으며 다른 프로세스 이름 (예 : 데몬)은 가져올 수 없습니다. – 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; 
}