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