2014-04-08 56 views
0

執行「readDataToEndOfFile」方法後應用程序執行停止/掛起。請找到下面的代碼,如何解決這個問題執行停止在iOS中的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); 
} 
+1

可以定義一個連續流的「終結」?您必須終止tcpdump部分才能停止。 – borrrden

+0

@borrrden:我添加了-c 10在收到10個數據包後退出,代碼如下,我怎麼能在30秒後退出它而不是10個數據包? –

+0

[task setArguments:[[NSArray alloc] initWithObjects:@「 - c」,@「10」,@「 - i」,@「​​en1」,@「 - A」,@「 - vvv」 ,@「www.facebook.com」,零]]; –

回答

0

嘗試使用availableData代替readDataToEndOfFile

NSFileHandle *fileHandle=notif.object; 
NSData *data = [fileHandle availableData]; 
if (data) 
{ 
// do something 
}