views:

487

answers:

2

Hello everyone

I'm writing a small app to keep track of local mono sites. I'm mostly writing this for my own use and to play around with xcode

To start the server i run the following code:

[task setLaunchPath: @"/usr/bin/xsp2"];
NSArray *arguments = [NSArray arrayWithObjects: @"--root", [[document selectedSite] valueForKey:@"path"], @"--nonstop" ,nil];
[task setArguments: arguments];
NSLog(@"argument: %@", arguments);

NSPipe *pipe = [NSPipe pipe];
[task setStandardOutput:pipe];

NSFileHandle *file = [pipe fileHandleForReading];

[task launch];

NSData *inData = nil; 
while ((inData = [file availableData]) && [inData length]) {
 NSLog(@"%@", [[NSString alloc] initWithData:inData encoding:NSUTF8StringEncoding]);
}

[[document selectedSite] setValue:[NSNumber numberWithInt:1] forKey:@"active"];

[task release];
NSLog(@"opened site");

This results in an infinite loop, because the terminal never stops writing (I guess?). So my question is, how do i stop the loop? Please comment if I'm being unclear.

A: 

When you say "the terminal never stops writing (I guess?)", is that because the output keeps spewing out at the Terminal or in Console? If you're not getting loads of output, it's possible that call to availableData blocks — consult the documentation. You might try readDataToEndOfFile and see if it helps at all — you shouldn't have to put that in a loop unless it's an extremely large file (larger than UINT_MAX bytes).

Also, realize that you're (potentially) leaking an NSString with each iteration of the loop. Remember to autorelease the string inside the NSLog() call.

Quinn Taylor
Thanks for taking you time to leave an Quinn answer, and for the leak-hint :) when i use readDataToEndOfFile my app also chokes (spinning pizza-wheel of death). When i run the code in terminal it writes the follow snippet of textxsp2Listening on address: 0.0.0.0Root directory: /Users/MadsListening on port: 8080 (non-secure)Hit Return to stop the server.
Mads H
A: 

Yes .. availableData will block in your case because no data is available but it has not yet encountered end of file (which presumably would happen if the server closed its end of the pipe).

One solution would be just to listen for ouput on another thread. Your thread will never close, but it won't eat CPU either.

Ira Cooke