Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
667 views
in Technique[技术] by (71.8m points)

objective c - Cocoa wrapper for an interactive Unix command

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/gdb"];
[task launch];

I'm just wondering if there's a way to communicate with interactive command line tools such a as gdb. This would involve giving the command inputs based on user interaction (like run, kill or quit with gdb) and then reacting based on the information it outputs.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...