NSTask/NSPipe read from Unix command

耗尽温柔 提交于 2019-12-04 05:21:48
Michele Percich

Here is a working example of how I usually do it:

    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]){
        ...
    }   
}

Here's the async solution for getting the task output.

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

hope could help someone.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!