Execute a terminal command from a Cocoa app

后端 未结 12 2305
既然无缘
既然无缘 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:06

    kent's article gave me a new idea. this runCommand method doesn't need a script file, just runs a command by a line:

    - (NSString *)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];
    
        NSData *data = [file readDataToEndOfFile];
    
        NSString *output = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        return output;
    }
    

    You can use this method like this:

    NSString *output = runCommand(@"ps -A | grep mysql");
    

提交回复
热议问题