0

App execution stopped/hang after "readDataToEndOfFile" method executes. Please find the below code, how to fix this issue

    - (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);
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
Sudheer Kumar Palchuri
  • 2,919
  • 1
  • 28
  • 38

2 Answers2

0

try use availableData instead of readDataToEndOfFile

NSFileHandle *fileHandle=notif.object;
NSData *data = [fileHandle availableData];
if (data)
{
// do something
}
sage444
  • 5,661
  • 4
  • 33
  • 60
0

This is old and seems orphaned, but here's some possibly useful information for those who find themselves here.

Much of the Foundation relating to this issue has evolved. I didn't try to solve the exact problem above. I suspect it involves the waitUntilExit() method.

The NSTask is now the Process class (the documentation for the init method says it returns an NSTask).

Here's the current implementation of the above in Swift.

func tcDump() throws -> String {
    let task = Process()
    task.executableURL = URL(fileURLWithPath: "/usr/sbin/tcdump")
    task.arguments = ["-1", "-i", "en1", "-A", "-vvv", "host", "www.facebook.com"]
    let pipe = Pipe()
    task.standardOutput = pipe
    
    let fileHandle = pipe.fileHandleForReading
    try task.run()
    task.waitUntilExit()
    let data = fileHandle.readDataToEndOfFile()
    
    if let output = String(data: data, encoding: .utf8) {
        return output
    } else {
        FileHandle.standardError.write("problem with tcdump output\n".data(using:.utf8)!)
        throw NSError(domain: "error", code: 1, userInfo: nil)
    }
}
bshirley
  • 8,217
  • 1
  • 37
  • 43