NSTask / NSPipe odczytane z polecenia Unix
Piszę aplikację Cocoa, która musi wykonać program UNIX i odczytać jego wyjście, linia po linii, w miarę ich tworzenia. Ustawiłem NSTask i NSPipe jako takie:
task = [[NSTask alloc] init];
pipe = [NSPipe pipe];
[task setStandardOutput:pipe];
//... later ...
[task setArguments:...];
[task setLaunchPath:@"..."];
[task launch];
handle = [[task fileHandleForReading] retain];
Polecenie nie kończy się, dopóki program nie powie mu tego[task terminate]
. Próbowałem kilku metod odczytu z uchwytu, takich jak-readInBackgroundAndNotify
, while([(data = [handle availableData]) length] > 0)
, i-waitForDataInBackgroundAndNotify
, ale rura nigdy nie wydaje żadnych danych. Czy jest jakiś sposób, w jaki mogę „szturchnąć”NSTask
lubNSPipe
przepłukać dane?
EDYTOWAĆ: z-readInBackgroundAndNotify
:
[handle readInBackgroundAndNotify];
notification_block_t handlerBlock =
^(NSNotification *notification) {
NSData *data = [[notification userInfo]
objectForKey: NSFileHandleNotificationDataItem];
/*... do stuff ...*/
[self addNotification: handle block: handlerBlock];
};
[self addNotification: handler block: handlerBlock];
//...
- (void)addNotification:(id)handle block:(notification_block_t)block {
[[NSNotificationCenter defaultCenter]
addObserverForName: NSFileHandleReadCompletionNotification
object: handle
queue: [NSOperationQueue mainQueue]
usingBlock: block];
}
z-waitForDataInBackgroundAndNotify
:
[handle waitForDataInBackgroundAndNotify];
notification_block_t handlerBlock =
^(NSNotification *notification) {
NSData *data = [handle availableData];
/*... do stuff ...*/
};
[self addNotification: handler block: handlerBlock];
zwhile
pętla:
[self startProcessingThread: handle];
//...
- (void)startProcessingThread:(NSFileHandle *)handle {
[[NSOperationQueue mainQueue]
addOperation: [[[NSInvocationOperation alloc]
initWithTarget: self
selector: @selector(dataLoop:)
object: handle] autorelease]];
}
- (void)dataLoop:(NSFileHandle *)handle {
NSData *data;
while([(data = [handle availableData]) length] > 0) {
/*... do stuff ...*/
}
}
EDYCJA 2: Argumenty są ustawione w następujący sposób (polecenie totshark
):
NSArray *cmd = [NSArray arrayWithObjects:@"-R", @"http.request",
@"-Tfields", @"-Eseparator='|'",
@"-ehttp.host", @"-ehttp.request.method",
@"-ehttp.request.uri", nil];
cmd = [[cmd arrayByAddingObjectsFromArray:[self.ports map:^(id arg1, NSUInteger idx) {
return [NSString stringWithFormat:@"-d tcp.port==%d,http", [arg1 intValue]];
}]]
arrayByAddingObject:[@"dst " stringByAppendingString:
[self.hosts componentsJoinedByString:@" or dst "]]];
[self.tsharktask setArguments:cmd];