0
我试图检索使用如何使用Obj-C从TOP终端命令退出?
top -F -R -o cpu
指挥系统的CPU使用率是运行在终端精细但是我不能够得到使用的代码在Objective C中输出如下:
-(NSString*)runCommand:(NSString*)commandToRun;
{
NSTask *task;
task = [[NSTask alloc] init];
[task setLaunchPath: @"/bin/sh"];
NSArray *arguments = [NSArray arrayWithObjects:
@"-c" ,
[NSString stringWithFormat:@"%@", commandToRun],
nil];
NSLog(@"run command: %@",commandToRun);
[task setArguments: arguments];
NSPipe *pipe;
pipe = [NSPipe pipe];
[task setStandardOutput: pipe];
NSFileHandle *file;
file = [pipe fileHandleForReading];
[task launch];
NSData *data;
data = [file readDataToEndOfFile];
NSString *output;
output = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
return output;
}
我得到空字符串作为结果。
请建议我该怎么做。非常感谢。
“commandToRun”可能是一个字符串数组因为你必须分别传递命令和参数。并为'stderr'添加一个管道来获得潜在的错误。 – vadian
将使用'ps -vaA'而不是'top'来满足您的要求,不确定top将如何返回数据,因为它每秒更新 – Wain
@vadian如果您使用'-c',则该命令应该是单个字符串 – Wain