EDIT 1
This code is currently printing to the console. What I would like to do is get the data in a string (and stop the data going to the console) so I can parse it for specific information. I hope my question is clear. Please ask for clarification if needed :)
EDIT 2
Another alternative could be to print it to a file and then I could read from that file afterwards. Just don't want it printing to the console :)
Hello Lovely Intelligent Computer People!
Any help with this would be great.
So far I'm using NSTask to spawn a process:
NSTask *top_task;
top_t开发者_StackOverflow社区ask = [[NSTask alloc] init];
[top_task setLaunchPath: @"/usr/bin/top"];
NSArray *arguments;
arguments = [NSArray arrayWithObjects: @"-s", @"1",@"-l",@"3600",@"-stats",@"pid,cpu,time,command", nil];
[top_task setArguments: arguments];
NSPipe *pipe;
pipe = [NSPipe pipe];
[top_task setStandardInput:[NSPipe pipe]];
NSFileHandle *file;
file = [pipe fileHandleForReading];
[top_task launch];
Now, how do I grab the resulting information, let us say, in the form of an NSString?
Thanks for all and any help! :)
To launch your timer, you would want to do something like this:
NSTask *topTask = [NSTask new];
[topTask setLaunchPath:@"/usr/bin/top"];
[topTask setArguments:[NSArray arrayWithObjects:@"-s", @"1", @"-l", @"3600", @"-stats", @"pid,cpu,time,command", nil]];
NSPipe *outputPipe = [NSPipe pipe];
[topTask setStandardOutput:outputPipe];
[topTask launch];
So far, the code is really similar to what you've written, but you're going to have to add some more code to it. In order to get data every time top
updates, you have add this one line of code to the end:
[[outuputPipe fileHandleForReading] readToEndOfFileInBackgroundAndNotify];
That will send you an NSFileHandleReadToEndOfFileCompletionNotification
(if you register for it) every time top
updates with output, and you can query the notification object for the incoming data and convert it to an NSString like this:
NSString *outputString = [[[NSString alloc] initWithData:[[notification userInfo] objectForKey:NSFileHandleNotificationDataItem] encoding:NSUTF8StringEncoding] autorelease];
You can read up on this in the NSFileHandle documentation, and Interacting With the Operating System.
You set up a pipe for standard input for no apparent reason. I'd think you would want a pipe for standard output, and then read from that.
You might do it like that:
[top_task waitUntilExit];
NSString *string = [[NSString alloc] initWithData:[file readDataToEndOfFile] encoding:NSUnicodeStringEncoding] autorelease];
精彩评论