如何使用Obj-C从TOP终端命令中输出?

时间:2016-03-08 10:42:12

标签: objective-c

我正在尝试使用

检索系统的CPU使用率
top -F -R -o 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;
}

我得到了空字符串。

请建议我该怎么做。非常感谢。

1 个答案:

答案 0 :(得分:1)

我之前没有尝试使用top,我怀疑这个问题与每秒最高更新输出有关。在这种情况下,您可以尝试使用不同的top命令:

top -F -R -o cpu -l 1

或使用其他工具获取您想要的数据,例如ps

ps -vaA