Re: interactive command line apps
Re: interactive command line apps
- Subject: Re: interactive command line apps
- From: Andrew Bush <email@hidden>
- Date: Wed, 28 Sep 2005 11:12:13 +1200
Hi Sherm,
thanks for the help in getting started, that looks like a good way to
approach it so Ill take this and run :)
Yours cheerfully,
Andrew Bush
On 28, Sep 2005, at 8:31 AM, Sherm Pendley wrote:
On Sep 27, 2005, at 12:04 AM, Andrew Bush wrote:
is there some standard way to write a cocoa cli app that can be run,
and then accepts input via stdin, acts on it, and accepts further
input and so on?
or is it just as simple as putting a 'while 1' loop around the call
to stdin?
oh...I also need to have sockets doing stuff in the background of
this same app, if its just a while loop, do I need to make any
special calls to ensure that all the background tasks are doing their
stuff?
NSRunLoop is in Foundation, so it shouldn't require a connection to a
window server, but I haven't verified that.
If you use an NSRunLoop, you could use the built-in *inBackground
methods in NSFileHandle. You could do the same thing by creating and
managing your own background threads, but that's more work.
Here's an example of how I'd approach it. In main.m:
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
// Create the input handler
InputHandler *ih = [[[InputHandler alloc] init] autorelease];
while (![ih isFinished]) {
// Kick the run loop
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
beforeDate:[NSDate distantFuture]];
}
[pool release];
return 0;
}
The InputHandler class looks like this:
@implementation InputHandler
- (id) init {
if ((self = [super init])) {
// Read from stdin
NSFileHandle *inHandle = [NSFileHandle
fileHandleWithStandardInput];
// Listen for incoming data notifications
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(stdinDataAvailable)
name:NSFileHandleDataAvailableNotification
object:inHandle];
[inHandle waitForDataInBackgroundAndNotify];
}
return self;
}
- (BOOL) isFinished {
return finished;
}
- (void) stdinDataAvailable {
NSFileHandle *inHandle = [NSFileHandle
fileHandleWithStandardInput];
NSData *theData = [inHandle availableData];
if ([theData length] == 0) {
finished = YES;
return;
}
NSLog(@"Got data: %@", theData);
// Listen for more
[inHandle waitForDataInBackgroundAndNotify];
}
sherm--
Cocoa programming in Perl: http://camelbones.sourceforge.net
Hire me! My resume: http://www.dot-app.org
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Cocoa-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden