NSTask / NSPipe从Unix命令读(NSTask/NSPipe read from Un

2019-08-02 18:57发布

我写一个Cocoa应用程序,这需要执行一个UNIX编程和读取它的输出,一行行,因为它们产生的。 我成立了一个NSTask和NSPipe这样:

task = [[NSTask alloc] init];
pipe = [NSPipe pipe];
[task setStandardOutput:pipe];
//... later ...
[task setArguments:...];
[task setLaunchPath:@"..."];
[task launch];
handle = [[task fileHandleForReading] retain];

该命令不会终止,直到程序告诉它这样做[task terminate] 。 我已经尝试的从所述手柄读取的几种方法,诸如-readInBackgroundAndNotifywhile([(data = [handle availableData]) length] > 0)-waitForDataInBackgroundAndNotify ,但管道似乎从未得到的任何数据。 有一些方法可以让我“捅”了NSTaskNSPipe通过刷新数据?

编辑 :有-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];
}

-waitForDataInBackgroundAndNotify

[handle waitForDataInBackgroundAndNotify];
notification_block_t handlerBlock =
    ^(NSNotification *notification) {
        NSData *data = [handle availableData];
        /*... do stuff ...*/
    };
[self addNotification: handler block: handlerBlock];

while循环:

[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 ...*/
    }
}

EDIT 2:参数设置如下(该命令tshark ):

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];

Answer 1:

下面是如何我通常做的工作示例:

    task = [[NSTask alloc] init];
    [task setLaunchPath:...];
    NSArray *arguments;
    arguments = ...;
    [task setArguments:arguments];

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

    outFile = [outPipe fileHandleForReading];
    [outFile waitForDataInBackgroundAndNotify];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(commandNotification:)
                                                 name:NSFileHandleDataAvailableNotification 
                                               object:nil];    

    [task launch];


- (void)commandNotification:(NSNotification *)notification
{
    NSData *data = nil;
    while ((data = [self.outFile availableData]) && [data length]){
        ...
    }   
}


Answer 2:

以下是获取任务输出的异步解决方案。

task.standardOutput = [NSPipe pipe];
[[task.standardOutput fileHandleForReading] setReadabilityHandler:^(NSFileHandle *file) {
NSData *data = [file availableData]; // this will read to EOF, so call only once
NSLog(@"Task output! %@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);

// if you're collecting the whole output of a task, you may store it on a property
//maybe you want to appenddata
//[weakself.taskOutput appendData:data];
}];

希望可以帮助别人。



文章来源: NSTask/NSPipe read from Unix command