Skip to content

Instantly share code, notes, and snippets.

@ytlvy
Created October 7, 2015 09:44
Show Gist options
  • Save ytlvy/9fce2914cea018723854 to your computer and use it in GitHub Desktop.
Save ytlvy/9fce2914cea018723854 to your computer and use it in GitHub Desktop.
OS X获取当前运行的所有进程信息
//
// main.m
// process
//
// Created by piao on 15/8/13.
// Copyright (c) 2015年 piao. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <sys/sysctl.h>
#import <signal.h>
#import <unistd.h>
NSArray *processInfo() {
int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0};
size_t size;
int st = sysctl(mib, sizeof(mib) / sizeof(CTL_KERN), NULL, &size, NULL, 0);
struct kinfo_proc * process = NULL;
struct kinfo_proc * newprocess = NULL;
do {
size += size / 10;
newprocess = realloc(process, size);
if (!newprocess){
if (process){
free(process);
}
return nil;
}
process = newprocess;
st = sysctl(mib, sizeof(mib) / sizeof(CTL_KERN), process, &size, NULL, 0);
} while (st == -1 && errno == ENOMEM);
if (st == 0) {
if (size % sizeof(struct kinfo_proc) == 0){
unsigned long nprocess = size / sizeof(struct kinfo_proc);
if (nprocess){
NSMutableArray * array = [[NSMutableArray alloc] init];
for (unsigned long i = 0; i < nprocess; i++){
NSNumber *processID = [NSNumber numberWithInt:process[i].kp_proc.p_pid];
NSString *processName = [[NSString alloc] initWithFormat:@"%s", process[i].kp_proc.p_comm];
NSDictionary * dict = [[NSDictionary alloc] initWithObjects:[NSArray arrayWithObjects:processID, processName, nil]
forKeys:[NSArray arrayWithObjects:@"pid", @"name", nil]];
[array addObject:dict];
}
free(process);
return array;
}
}
}
return nil;
}
int main(int argc, const char * argv[]) {
@autoreleasepool {
// insert code here...
NSLog(@"process info:%@", processInfo());
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment