Cocoa wrapper for an interactive Unix command

前端 未结 2 1440
忘了有多久
忘了有多久 2020-12-17 22:21

Ok, so I know you can make an NSTask to run command line tools with Objective-C:

NSTask *task;
task = [[NSTask alloc] init];
[task setLaunchPath: @\"/usr/bin         


        
2条回答
  •  太阳男子
    2020-12-17 23:07

    You can use NSTask's setStandardInput:, setStandardOutput: and setStandardError: selectors in conjunction with NSPipe instances to communicate with the launched program.

    For example, to read the task's output:

    task = [[NSTask alloc] init];
    [task setStandardOutput: [NSPipe pipe]];
    [task setStandardError: [task standardOutput]]; // Get standard error output too
    [task setLaunchPath: @"/usr/bin/gdb"];
    [task launch];
    

    You can then obtain an NSFileHandle instance that you can use to read the task's output with:

    NSFileHandle *readFromMe = [[task standardOutput] fileHandleForReading]; 
    

    To set up a pipe for sending commands to gdb, you would add

    [task setStandardInput: [NSPipe pipe]];
    

    before you launch the task. Then you get the NSFileHandle with

    NSFileHandle *writeToMe = [[task standardInput] fileHandleForWriting];
    

提交回复
热议问题