使用NSTask时处理错误

时间:2013-01-19 11:19:45

标签: objective-c apache nstask

作为一个学习项目,我正在为Apache stresstesting命令行工具“ab”编写一个简单的gui。它需要一个完整的URL,包括诸如index.html或simular之类的文件名作为其参数之一。如果未指定文件名“ab”echos“Invalid url”并显示可用标志列表。

我想抓住这个“错误”,并尝试使用NSTasks标准输出。真的无法让它发挥作用。这甚至可以归类为会导致标准错误的错误吗?

除了在启动NSTask之前验证URL输入之外,您认为我可以阻止或者更确切地捕获此错误吗?

我的简单代码:

- (void) stressTest:(NSString *)url withNumberOfRequests:(int)requests sendSimultaneously:(int)connections {

    NSBundle *mainBundle = [NSBundle mainBundle];
    NSString *abPath = [[mainBundle bundlePath] stringByAppendingString:@"/Contents/Resources/ab"];

    NSString* requestsStr = [NSString stringWithFormat:@"%i", requests];
    NSString* connectionsStr = [NSString stringWithFormat:@"%i", connections];

    // Init objects for tasks and pipe
    NSTask *abCmd = [NSTask new];
    NSPipe *outputPipe = [NSPipe pipe];
    [abCmd setLaunchPath:abPath];
    [abCmd setArguments:[NSArray arrayWithObjects:@"-n", requestsStr, @"-c", connectionsStr, url, nil]];
    [abCmd setStandardOutput:outputPipe];
    [abCmd launch];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(readCompleted:) name:NSFileHandleReadToEndOfFileCompletionNotification object:[outputPipe fileHandleForReading]];
    [[outputPipe fileHandleForReading] readToEndOfFileInBackgroundAndNotify];
}

- (void)readCompleted:(NSNotification *)notification {

    NSString * tempString = [[NSString alloc] initWithData:[[notification userInfo] objectForKey:NSFileHandleNotificationDataItem] encoding:NSASCIIStringEncoding];
   [resultTextOutlet setString:tempString];
   [[NSNotificationCenter defaultCenter] removeObserver:self name:NSFileHandleReadToEndOfFileCompletionNotification object:[notification object]];
}

1 个答案:

答案 0 :(得分:2)

ab将其错误消息(包括使用信息)写入标准错误。您目前只阅读标准输出。要访问错误消息或使用信息,您需要分配一秒NSPipe,将其传递给-[NSTask setStandardError:],然后从中读取数据。