Created
February 19, 2019 02:07
-
-
Save kim4apple/e0c0e6e8b92d1610501adfeb59adc485 to your computer and use it in GitHub Desktop.
Get process path with pid using libproc.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import <libproc.h> | |
#import <sys/proc_info.h> | |
@interface ProcessUtil : NSObject | |
+ (NSArray <NSNumber *> *)loadProcessIds; | |
+ (NSString *)pathWithPid:(int)pid; | |
@end | |
@implementation ProcessUtil | |
+ (NSArray <NSNumber *> *)loadProcessIds { | |
int n = proc_listpids(PROC_ALL_PIDS, 0, NULL, 0); | |
NSMutableArray *pidList = [NSMutableArray array]; | |
pid_t pids[n]; | |
bzero(pids, sizeof(pids)); | |
proc_listpids(PROC_ALL_PIDS, 0, pids, (int)sizeof(pids)); | |
for (int i = 0; i < n; ++i) { | |
if (pids[i] == 0) { continue; } | |
[pidList addObject:@(pids[i])]; | |
} | |
return pidList; | |
} | |
+ (NSString *)pathWithPid:(int)pid { | |
NSString *path = nil; | |
char pathBuffer[PROC_PIDPATHINFO_MAXSIZE]; | |
bzero(pathBuffer, PROC_PIDPATHINFO_MAXSIZE); | |
proc_pidpath(pid, pathBuffer, sizeof(pathBuffer)); | |
if (strlen(pathBuffer) > 0) { | |
path = [NSString stringWithFormat:@"%s", pathBuffer]; | |
} | |
return path; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment