Re: NSFileHandle stdin sends ∞ notifications of 0 bytes available
Re: NSFileHandle stdin sends ∞ notifications of 0 bytes available
- Subject: Re: NSFileHandle stdin sends ∞ notifications of 0 bytes available
- From: Jerry Krinock <email@hidden>
- Date: Thu, 12 Jun 2014 16:53:56 -0700
On 2014 Jun 12, at 15:35, Greg Parker <email@hidden> wrote:
> If you get back an empty data object you are at end of file, and you should not call -waitForDataInBackgroundAndNotify again.
Thank you, Greg. I thought that same thing a couple hours ago. But it trades one problem for another…
* * *
To implement your suggestion, I moved the line
[input waitForDataInBackgroundAndNotify] ;
up a few lines, into the block that is conditioned by if([data length] > 0)
Indeed, doing that fixes the infinite loop, but then there is no response to subsequent stdin because, presumably, without -waitForDataInBackgroundAndNotify, it’s not waiting and not notifying.
That’s why I focused on the weird zero-byte notification as being the problem. It seems like NSFileHandle, that it does not reset itself to "no data available" after I’ve read the piped-in initial stdin.
Any more ideas? Meantime, I’ll pound on it some more.
Jerry
P.S. Either this revised code or the original code works OK if there is no stdin piped to the tool.
REVISED CODE:
int main(int argc, const char * argv[]) {
@autoreleasepool {
/* -[NSFileManager waitForDataInBackgroundAndNotify] docs say I need
an "active run loop". I don't know what they mean by "active".
Maybe this will help (it didn't). */
NSDate* verySoon = [NSDate dateWithTimeIntervalSinceNow:0.01] ;
[[NSRunLoop mainRunLoop] runUntilDate:verySoon] ;
NSFileHandle* input = [NSFileHandle fileHandleWithStandardInput] ;
[input waitForDataInBackgroundAndNotify] ;
NSNotificationCenter* dc = [NSNotificationCenter defaultCenter] ;
[dc addObserverForName:NSFileHandleDataAvailableNotification
object:input
queue:nil
usingBlock:^(NSNotification* note) {
NSFileHandle* input ;
input = [NSFileHandle fileHandleWithStandardInput] ;
NSData* data = [input availableData] ;
NSLog(@"Got noted of %ld bytes", (long)[data length]) ;
if ([data length] > 0) {
NSFileHandle* output ;
output = [NSFileHandle fileHandleWithStandardOutput] ;
[output writeData:[NSData dataWithBytes:"--> "
length:4]] ;
[output writeData:data] ;
[input waitForDataInBackgroundAndNotify] ;
}
}] ;
/*SSYDBL*/ NSLog(@"Running run loop") ;
[[NSRunLoop mainRunLoop] run] ;
}
return 0 ;
}
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden