2016-03-08 97 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

'錯誤打開終端:未知。這是我得到的錯誤。 –