// // PsRunner.m // Top // // Created by Simon Brenner on 2008-01-07. // Copyright 2008 __MyCompanyName__. All rights reserved. // #import "PsRunner.h" @implementation PsRunner +(NSArray*)defaultOptions { return [NSArray arrayWithObjects: @"-A", @"-w", @"-w", NULL]; } +(NSString*)defaultFormat { return @"pid pcpu command"; } +(NSString*)pathToResource:(NSString*)resource { return [[NSBundle bundleForClass: [PsRunner class]] pathForResource: resource ofType: nil]; } -(id)initWithOptions: (NSArray*)options_ andFormat: (NSString*)format_ { options = [options_ retain]; format = [format_ retain]; return self; } -(id)initWithOptions:(NSArray*)options_ { return [self initWithOptions: options_ andFormat: [PsRunner defaultFormat]]; } -(id)initWithFormat:(NSString*)format_ { return [self initWithOptions: [PsRunner defaultOptions] andFormat: format_]; } -(id)init { return [self initWithOptions: [PsRunner defaultOptions] andFormat: [PsRunner defaultFormat]]; } +(NSString*)runWithOptions: (NSArray*)options andFormat: (NSString*)format { NSMutableArray *args = [[NSMutableArray alloc] initWithArray: options]; [args addObjectsFromArray: [NSArray arrayWithObjects: @"-o", format, NULL]]; NSTask *task = [NSTask new]; NSPipe *stdoutPipe = [NSPipe new]; [task setArguments: args]; [task setLaunchPath: [PsRunner pathToResource: @"Main"]]; [task setStandardOutput: stdoutPipe]; [task launch]; NSData *data = [[stdoutPipe fileHandleForReading] readDataToEndOfFile]; NSString *string = [NSString stringWithCString: [data bytes]]; [data release]; [stdoutPipe release]; [task waitUntilExit]; [task release]; return string; } -(id)run { NSString *string = [PsRunner runWithOptions: options andFormat: format]; NSMutableArray *lines = [NSMutableArray arrayWithArray: [string componentsSeparatedByString: @"\n"]]; for (int i = 0; i < [lines count]; i++) [lines replaceObjectAtIndex: i withObject: [NSMutableArray arrayWithArray: [[lines objectAtIndex: i] componentsSeparatedByString: @"\t"]]]; [lines makeObjectsPerformSelector: @selector(removeLastObject)]; NSArray *keys = [lines objectAtIndex: 0]; [lines removeObjectAtIndex: 0]; printf("Keys: %s\n", [[keys description] cString]); NSMutableArray *ret = [NSMutableArray new]; for (int i = 0; i < [lines count]; i++) { NSArray *vals = [lines objectAtIndex: i]; NSDictionary *dict = NULL; @try { dict = [NSDictionary dictionaryWithObjects: vals forKeys: keys]; } @catch (NSException *exc) { printf("ERR!\nkeys: %s\n vals: %s\n", [[keys description] cString], [[vals description] cString]); } if (dict) { printf("::\n"); printf("\t%s\n", [[dict description] cString]); [ret addObject: dict]; [dict release]; } } return ret; } @end