2016-03-08 62 views
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; 
} 

我得到空字符串作为结果。

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

+0

“commandToRun”可能是一个字符串数组因为你必须分别传递命令和参数。并为'stderr'添加一个管道来获得潜在的错误。 – vadian

+1

将使用'ps -vaA'而不是'top'来满足您的要求,不确定top将如何返回数据,因为它每秒更新 – Wain

+0

@vadian如果您使用'-c',则该命令应该是单个字符串 – Wain

回答

1

我还没有尝试过用这种方式使用top,我怀疑这个问题是与每秒钟更新输出顶端有关的。在这种情况下,你可以尝试不同的top命令:

top -F -R -o cpu -l 1 

,或者使用不同的工具来得到你想要的数据,如ps

ps -vaA 
+0

'错误打开终端:未知。这是我得到的错误。 –