Async execution of shell command not working properly

后端 未结 2 1215
忘掉有多难
忘掉有多难 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条回答
  •  梦毁少年i
    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;
    }];
    

提交回复
热议问题