Async execution of shell command not working properly

后端 未结 2 1216
忘掉有多难
忘掉有多难 2021-01-21 13:31

So, this is my code :

- (void)runCmd:(NSString *)cmd withArgs:(NSArray *)args
{
    NSLog(@\"\\nRunning ::\\n\\tCmd : %@\\n\\tArgs : %@\",cmd, args);
    [theSpi         


        
相关标签:
2条回答
  • 2021-01-21 13:53

    You use readInBackgroundAndNotify to schedule your reading. This method reads only one buffer full of data and notifies. You either need to call readInBackgroundAndNotify in your notification method again to read more data or you need to use readToEndOfFileInBackgroundAndNotify if you want to receive all the data at once.

    0 讨论(0)
  • 2021-01-21 13:53

    There's a new API since 10.7, so you can avoid using NSNotifications.

    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
        [self.taskOutput appendData:data];
    }];
    

    IMPORTANT:

    When your task terminates, you have to set readabilityHandler block to nil; otherwise, you'll encounter high CPU usage, as the reading will never stop.

    [task setTerminationHandler:^(NSTask *task) {
    
        // do your stuff on completion
    
        [task.standardOutput fileHandleForReading].readabilityHandler = nil;
        [task.standardError fileHandleForReading].readabilityHandler = nil;
    }];
    
    0 讨论(0)
提交回复
热议问题