Execute a terminal command from a Cocoa app

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

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

12条回答
  •  佛祖请我去吃肉
    2020-11-22 06:56

    You can use NSTask. Here's an example that would run '/usr/bin/grep foo bar.txt'.

    int pid = [[NSProcessInfo processInfo] processIdentifier];
    NSPipe *pipe = [NSPipe pipe];
    NSFileHandle *file = pipe.fileHandleForReading;
    
    NSTask *task = [[NSTask alloc] init];
    task.launchPath = @"/usr/bin/grep";
    task.arguments = @[@"foo", @"bar.txt"];
    task.standardOutput = pipe;
    
    [task launch];
    
    NSData *data = [file readDataToEndOfFile];
    [file closeFile];
    
    NSString *grepOutput = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
    NSLog (@"grep returned:\n%@", grepOutput);
    

    NSPipe and NSFileHandle are used to redirect the standard output of the task.

    For more detailed information on interacting with the operating system from within your Objective-C application, you can see this document on Apple's Development Center: Interacting with the Operating System.

    Edit: Included fix for NSLog problem

    If you are using NSTask to run a command-line utility via bash, then you need to include this magic line to keep NSLog working:

    //The magic line that keeps your log where it belongs
    task.standardOutput = pipe;
    

    An explanation is here: https://web.archive.org/web/20141121094204/https://cocoadev.com/HowToPipeCommandsWithNSTask

提交回复
热议问题