Execute a terminal command from a Cocoa app

后端 未结 12 2383
既然无缘
既然无缘 2020-11-22 06:34

How can I execute a terminal command (like grep) from my Objective-C Cocoa application?

12条回答
  •  清歌不尽
    2020-11-22 07:03

    In addition to the several excellent answers above, I use the following code to process the output of the command in the background and avoid the blocking mechanism of [file readDataToEndOfFile].

    - (void)runCommand:(NSString *)commandToRun
    {
        NSTask *task = [[NSTask alloc] init];
        [task setLaunchPath:@"/bin/sh"];
    
        NSArray *arguments = [NSArray arrayWithObjects:
                              @"-c" ,
                              [NSString stringWithFormat:@"%@", commandToRun],
                              nil];
        NSLog(@"run command:%@", commandToRun);
        [task setArguments:arguments];
    
        NSPipe *pipe = [NSPipe pipe];
        [task setStandardOutput:pipe];
    
        NSFileHandle *file = [pipe fileHandleForReading];
    
        [task launch];
    
        [self performSelectorInBackground:@selector(collectTaskOutput:) withObject:file];
    }
    
    - (void)collectTaskOutput:(NSFileHandle *)file
    {
        NSData      *data;
        do
        {
            data = [file availableData];
            NSLog(@"%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] );
    
        } while ([data length] > 0); // [file availableData] Returns empty data when the pipe was closed
    
        // Task has stopped
        [file closeFile];
    }
    

提交回复
热议问题