作为一个学习项目,我为 Apache 压力测试命令行工具“ab”编写了一个简单的 gui。它需要一个完整的 URL,包括一个文件名,例如 index.html 或 simular,作为它的参数之一。如果未指定文件名,“ab”会回显“无效 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]];
}