NSTask生成顶部进程。如何提取数据? [英] NSTask spawns top process. How to extract data?

查看:133
本文介绍了NSTask生成顶部进程。如何提取数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编辑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可爱的智能计算机人!

Hello Lovely Intelligent Computer People!

任何帮助将是伟大的。

Any help with this would be great.

到目前为止,我使用NSTask生成一个进程:

So far I'm using NSTask to spawn a process:

NSTask *top_task;
top_task = [[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];

现在,如何以NSString的形式获取生成的信息?

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];

到目前为止,代码和你写的很相似,必须添加一些更多的代码。为了在每次 top 更新时获取数据,请将以下一行代码添加到结尾:

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];

这会向您发送一个 NSFileHandleReadToEndOfFileCompletionNotification 你注册它)每次顶部更新与输出,你可以查询通知对象的传入数据,并将其转换为NSString如下:

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];






href =http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSFileHandle_Class/Reference/Reference.html =nofollow noreferrer> NSFileHandle说明文件,以及与操作系统

这篇关于NSTask生成顶部进程。如何提取数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆