【发布时间】:2014-04-08 06:17:56
【问题描述】:
“readDataToEndOfFile”方法执行后应用程序执行停止/挂起。请找到以下代码,如何解决此问题
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSTask *task = [[NSTask alloc] init];
[task setLaunchPath: @"/usr/sbin/tcpdump"];
[task setArguments: [[NSArray alloc] initWithObjects:@"-l", @"-i",@"en1",@"-A",@"-vvv",@"host",@"www.facebook.com", nil]];
NSPipe *pipe= [NSPipe pipe];
[task setStandardOutput: pipe];
NSFileHandle *fileHandle = [pipe fileHandleForReading];
[task launch];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receivedData:) name:NSFileHandleDataAvailableNotification object:fileHandle];
[fileHandle waitForDataInBackgroundAndNotify];
}
- (void)receivedData:(NSNotification *)notif {
NSFileHandle *fileHandle=notif.object;
NSData *data = [fileHandle readDataToEndOfFile];
NSString *output = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog(@"result: %@", output);
}
【问题讨论】:
-
你能定义连续流的“结束”吗?您必须终止 tcpdump 部分才能停止。
-
@borrrden:我添加了-c 10 以在收到 10 个数据包后退出,代码如下,如何在 30 秒后退出而不是 10 个数据包?
-
[task setArguments: [[NSArray alloc] initWithObjects:@"-c",@"10", @"-i",@"en1",@"-A",@"- vvv",@"host",@"www.facebook.com", nil]];
-
检查 man 的 tcpdump。或者尝试在 30 秒后杀死 NSTask。
标签: ios nstask nsfilehandle